#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: expandtab sw=4 ts=4 sts=4:
'''
Gammu man page generator
'''
__author__ = 'Michal Čihař'
__email__ = 'michal@cihar.com'
__license__ = '''
Copyright © 2003 - 2010 Michal Čihař

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''

# Configuration

'''
Path to gammu binary.
'''
BIN_PATH = 'build/gammu/gammu'
'''
Error listing binary.
'''
ERROR_LIST_PATH = 'build/tests/dump-error-codes'

'''
Output path where man page will be stored.
'''
OUT_PATH = 'docs/user/gammu.1'


# Man page data

HEADER = '.TH "GAMMU" "1" "%(date)s" "Gammu %(version)s" "Gammu Documentation"\n'
SECTION = '\n.SH "%s"\n'
SUBSECTION = '\n.SS "%s"\n'
PARAGRAPH = '.P\n%s\n'
COMMAND = '.TP\n.BI "%s" " %s"\n%s\n'
COMMAND_NOPARAM = '.TP\n.BI "%s"\n%s\n'

# Fixed parts

SEE_ALSO = '''
.P
gammu\\-smsd(1), gammu\\-smsd\\-inject(1), gammurc(5), jadmaker(1)

Some more hints can be found in README file or on wiki <http://www.gammu.org/>.

Related programs which can be used with GSM modem:

cu(1), gnokii(1), minicom(1)

Graphical interfaces for Gammu:

wammu(1), gmobilemedia(1)

'''

AUTHOR = '''
.P 
You can contact authors on <gammu-users@lists.sourceforge.net>.

.P 
\\fIMichal Cihar\\fR
<michal@cihar.com>
is current project maintainer and contributor of most of AT and OBEX
code.

.P 
\\fIMarcin Wiacek\\fR
<marcin@mwiacek.com>
is project iniciator and contributor of most Nokia code.

.P
As this project grew from Gnokii, we would like to thanks all Gnokii
developers, especially \\fIPavel Janik\\fR, \\fIPawel Kot\\fR
and \\fIManfred Jonsson\\fR (see CREDITS from Gnokii for all their
contributor).

.P
Many other people have helped with various features, check ChangeLog for
more details.
'''

FILES = '''
.P 
\\fI~/.gammurc\\fP
.br
\\fI/usr/share/doc/gammu/*\\fP
.br
\\fI/dev/ircomm?\\fP
.br
\\fI/dev/ttyS?\\fP
.br
\\fI/dev/ttyACM?\\fP
'''

RETURN_VALUES = '''
.P 
gammu returns 0 on success. In case of failure non zero code is 
returned. 

.SS 1
Out of memory or other critical error.

.SS 2
Invalid command line parameters.

.SS 3
Failed to open file specified on command line.

.SS 4
Program was interrupted.

.SS 98
Gammu library version mismatch.

.SS 99
Functionality has been moved. For example to gammu-smsd(1).

Errors codes greater than 100 map to the GSM_Error 
values increased by 100:

'''

EXAMPLE = '''

.SS Configuration

.P 
To check it out, you need to have configuration file for gammu, see 
gammurc(5) for more details about it.

.SS Sending messages

.TP
Save text message up to standard 160 chars:

.RS
.sp
.nf
.ne 7
echo "All your base are belong to us" | gammu savesms TEXT
.fi
.sp
.RE
.PP

or 

.RS
.sp
.nf
.ne 7
gammu savesms TEXT \\-text "All your base are belong to us"
.fi
.sp
.RE
.PP

.TP
Save long text message:

.RS
.sp
.nf
.ne 7
echo "All your base are belong to us" | gammu savesms TEXT \\-len 400
.fi
.sp
.RE
.PP

or 

.RS
.sp
.nf
.ne 7
gammu savesms TEXT \\-len 400 \\-text "All your base are belong to us"
.fi
.sp
.RE
.PP

or

.RS
.sp
.nf
.ne 7
gammu savesms EMS \\-text "All your base are belong to us"
.fi
.sp
.RE
.PP

.TP
Save some funky message with predefined sound and animation from 2 bitmaps:

.RS
.sp
.nf
.ne 7
gammu savesms EMS \\-text "Greetings" \\-defsound 1 \\-text "from Gammu"
\\-tone10 axelf.txt \\-animation 2 file1.bmp file2.bmp
.fi
.sp
.RE
.PP

.TP
Save protected message with ringtone:

.RS
.sp
.nf
.ne 7
gammu savesms EMS \\-protected 2 \\-variablebitmaplong ala.bmp
\\-toneSElong axelf.txt \\-toneSE ring.txt
.fi
.sp
.RE
.PP

.SS Backups

If you will backup settings to Gammu text file, it will be possible to edit
it. It's easy: many things in this file will be written double - once in Unicode,
once in ASCII. When you will remove Unicode version Gammu will use ASCII
on \\fBrestore\\fR (and you can easy edit ASCII text) and will convert it
according to your OS locale. When will be available Unicode version of text,
it will be used instead of ASCII (useful with Unicode phones - it isn't important,
what locale is set in computer and no conversion Unicode \\-> ASCII and ASCII \\->
Unicode is done).

You can use any editor with regular expressions function to edit backup text
file. Examples of such editors can be vim <http://www.vim.org/> or TextPad
<http://www.textpad.com/> which both do support regular expressions.

.TP
Remove info about voice tags

Find: ^Entry\\\\([0\\-9][0\\-9]\\\\)VoiceTag = \\\\(.*\\\\)\\\\n

Replace:

.TP
Change all numbers starting from +3620, +3630, +3660, +3670 to +3620

Find: Type = NumberGeneral\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)Text = "\\\\+36\\\\(20\\\\|30\\\\|60\\\\|70\\\\)\\\\n

Replace: Type = NumberMobile\\\\nEntry\\\\1Text = "\\\\+3620

.TP
Change phone numbers type to mobile for numbers starting from +3620, +3630,... and removing the corresponding TextUnicode line

Find: Type = NumberGeneral\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)Text = "\\\\+36\\\\([2367]0\\\\)\\\\([^\\\\"]*\\\\)"\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)TextUnicode = \\\\([^\\\\n]*\\\\)\\\\n

Replace: Type = NumberMobile\\\\nEntry\\\\1Text = "\\\\+36\\\\2\\\\3"\\\\n

'''

NAME = '''
.P
Gammu - Does some neat things with your cellular phone or modem.
'''

DESCRIPTION = '''
.P
This program is a tool for mobile phones. Many vendors and phones
are supported, for actual listing see <http://wammu.eu/phones/>.
'''

COPYRIGHT = '''
Copyright \(co 2003 - 2010 Marcin Wiacek, Michal Cihar and other authors.
License GPLv2: GNU GPL version 2 <http://www.gnu.org/licenses/old\\-licenses/gpl\\-2.0.html>
.br
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
'''

BUGS = '''
There are definitely many bugs, reporting to author is welcome. Please include
some useful information when sending bug reports (especially debug logs,
operating system, it's version and phone information are needed).

.P
To generate debug log, enable it in gammurc (alternatively you can
do it on command line using \\-d textall \\-f /tmp/gammu.log):

.RS
.sp
.nf
.ne 7
[gammu]
YOUR CONNECTION SETTINGS
logfile = /tmp/gammu.log
logformat = textall
.fi
.sp
.RE
.PP

With this settings, Gammu generates /tmp/gammu.log on each connection to
phone and stores dump of communication there. You can also find some
hints for improving support for your phone in this log.

See <http://wammu.eu/support/bugs/> for more information on reporting bugs.

Please report bugs to <http://bugs.cihar.com>.
'''

SMS_SEND_HELP = 'Sends a message, for description of message specific parameters see \\fB%s\\fR.\n\n'
SMS_COMMON_HELP = '\n\nFor description of shared parameters see \\fBCommon parameters for sendsms and savesms\\fR.\n\n'

# Commands help, initially generated from original gammu man page

HELP = {}
HELP['help'] = '''Print help. By default general help is printed, but you can
also specify a help category to get more detailed help on some topic.
''' 
HELP['version'] = '''Print version information and license.
'''
HELP['features'] = '''Print information about compiled in features.
'''
HELP['checkversion'] = '''Checks whether there is newer Gammu version
available online (if Gammu has been compiled with CURL). If you pass
additional parameter \\fBSTABLE\\fR, only stable versions will be checked.
'''
HELP['identify'] = '''Show the most important phone data.
''' 
HELP['networkinfo'] = '''Show information about network status from the phone.
''' 
HELP['getlocation'] = '''Gets network information from phone (same as networkinfo)
and prints location (latitude and longitude) based on information from 
OpenCellID <http://opencellid.org>.
''' 
HELP['monitor'] = '''Get phone status and writes continuously to standard output. Press Ctrl+C
to break this state.
'''
HELP['reset SOFT|HARD'] = '''Make phone reset: soft (without asking for PIN) or hard (with PIN).

\\fINote:\\fR some phones will make hard reset even with \\fBSOFT\\fR option.
'''
HELP['resetphonesettings'] = '''Reset phone settings. \\fIBE CAREFULL !!!!\\fR

\\fBPHONE:\\fR
.br

\\fBDEV:\\fR
.br

\\fBALL:\\fR 

Clear user settings
.br
* removes or set logos to default
.br
* set default phonebook and other menu settings
.br
* clear T9 words,
.br
* clear call register info
.br
* set default profiles settings 
.br
* clear user ringtones

\\fBUIF:\\fR
.br
* changes like after \\fBALL\\fR
.br
* disables netmon and PPS (all "hidden" menus)

\\fBFACTORY:\\fR
.br
* changes like after \\fBUIF\\fR
.br
* clear date/time
'''
HELP['presskeysequence'] = '''Press specified key sequence on phone keyboard

\\fBmM\\fR - Menu
.br
\\fBnN\\fR - Names key
.br
\\fBpP\\fR - Power
.br
\\fBuU\\fR - Up
.br
\\fBdD\\fR - Down
.br
\\fB+\\-\\fR - +\\-
.br
\\fBgG\\fR - Green
.br
\\fBrR\\fR - Red
.br
\\fB123456789*0#\\fR is numeric keyboard
'''
HELP['getdisplaystatus'] = ''''''
HELP['getprofile'] = ''''''
HELP['setautonetworklogin'] = ''''''
HELP['getsecuritystatus'] = '''Show, if phone wait for security code (like PIN, PUK, etc.) or not
'''
HELP['entersecuritycode'] = '''Allow to enter security code from PC. When code is \\-, it is read from stdin.
'''
HELP['listnetworks'] = '''Show names/codes of GSM networks known for Gammu
'''
HELP['getfmstation'] = '''Show info about FM stations in phone
'''
HELP['getgprspoint'] = ''''''
HELP['getfiles'] = '''Retrieve files with given IDs from a phone filesytem.'''
HELP['getfilefolder'] = '''Retrieve files or all files from folder with given IDs from a phone filesytem.'''
HELP['getfilesystemstatus'] = '''Display info filesystem status - number of
bytes available, used or used by some specific content.'''
HELP['getfilesystem'] = '''Display info about all folders and files in phone memory/memory card. By default there is tree displayed, you can change it:

.B \\-flatall
there are displayed full file/folder details like ID (first parameter in line)

.B \\-flat

Please note, that in some phones (like N6230) content of some folders (with more files) can be cut (only part of files will be displayed) for example on infrared connection. This is not Gammu issue, but phone firmware problem.
'''
HELP['getfolderlisting'] = '''
Display files and folders available in folder with given folder ID. You can get ID's using getfilesystem \\-flatall.

Please note, that in some phones (like N6230) content of some folders (with more files) can be cut (only part of files will be displayed) for example on infrared connection. This is not Gammu issue, but phone firmware problem.
'''
HELP['getrootfolders'] = '''
Display info about drives available in phone/memory card.
'''
HELP['deletefolder'] = '''Delete folder with given ID.'''
HELP['deletefiles'] = '''Delete files with given IDs.'''
HELP['addfolder'] = '''Create a folder in phone with specified name in a
folder with specified folder ID.'''
HELP['sendfile'] = '''Sends file to a phone. It's up to phone to decide where
to store this file and how to handle it (for example when you send vCard or
vCalendar, most of phones will offer you to import it.
'''
HELP['addfile'] = '''Add file with specified name to folder with specified folder ID.

.B \\-type 
- file type was required for filesystem 1 in Nokia phones (current filesystem 2 doesn't need this)

.B \\-readonly, \\-protected, \\-system, \\-hidden
- you can set readonly, protected (file can't be for example forwarded from phone menu), system and hidden (file is hidden from phone menu) file attributes

.B \\-newtime 
- after using it date/time of file modification will be set to moment of uploading 

'''
HELP['nokiaaddplaylists'] = '''
Goes through phone memory and generated playlist for all music files found.

To manually manage playlists:

    gammu addfile a:\\\\predefplaylist filename.m3u

Will add playlist filename.m3u

    gammu getfilesystem

Will get list of all files (including names of files with playlists)

    gammu deletefiles a:\\\\predefplaylist\\\\filename.m3u

Will delete playlist filename.m3u

Format of m3u playlist is easy (standard mp3 playlist):

First line is #EXTM3U, next lines contain  names of files (b:\\\\file1.mp3,
b:\\\\folder1\\\\file2.mp3, etc.). File needs t have '\\\\r\\\\n' terminated lines. So
just run unix2dos on the resulting file before uploading it your your phone.
'''
HELP['nokiaaddfile APPLICATION|GAME'] = '''Install the *.jar/*.jad file pair of a midlet in the application or game menu of the phone. You need to specify filename without the jar/jad suffix, both will be added automatically.

The option
.I \-overwrite
deletes the application's .jad and .jar files bevor installing, but doesn't delete the application data. Option
.I \-overwriteall
will also delete all data. Both these options work only for Application or Game upload.

\\fIExample:\\fR gammu nokiaaddfile Application Alien will read Alien.JAD and Alien.JAR and add to Applications

\\fIExample:\\fR gammu nokiaaddfile Tones file.mid will read file.mid and add to Tones folder

You can use jadmaker(1) to generate a .jad file from a .jar file.
''' 
HELP['getdatetime'] = '''Get date and time from phone
''' 
HELP['setdatetime'] = '''Set date and time in phone to date and time set in computer. Please 
note, that this option doesn't show clock on phone screen. It only set
date and time.

\\fITIP:\\fR you can make such synchronization each time, when will connect
your phone and use Gammu. See gammurc(5) for details.
''' 
HELP['getalarm'] = '''Get alarm from phone, if no location is specified,
1 is used.
'''
HELP['setalarm'] = '''Sets repeating alarm in phone on selected time.''' 
HELP['getallmemory'] = '''Get all memory locations from phone. For memory
types see \\fBgetmemory\\fR.'''
HELP['getmemory'] = '''Get memory location from phone. 

Locations are numerated from 1.

\\fBDC\\fR = Dialled calls
.br
\\fBMC\\fR = Missed calls
.br
\\fBRC\\fR = Received calls
.br
\\fBON\\fR = Own numbers
.br
\\fBVM\\fR = voice mailbox
.br
\\fBSM\\fR = SIM phonebook
.br
\\fBME\\fR = phone internal phonebook
.br
\\fBFD\\fR = fixed dialling
.br
\\fBSL\\fR = sent SMS log
'''
HELP['searchmemory'] = '''Scans all memory entries for given text. It performs
case insensitive substring lookup. You can interrupt searching by pressing
Ctrl+C.'''
HELP['deleteallmemory'] = '''Deletes all entries from specified memory type.'''
HELP['deletememory'] = '''Deletes entries in specified range from specified memory type.'''
HELP['listmemorycategory'] = ''''''
HELP['senddtmf'] = '''Plays DTMF sequence. In some phones available only during calls
'''
HELP['getspeeddial'] = '''''' 
HELP['getsms'] = '''Get SMS. 

Locations are numerated from 1.

Folder 0 means that sms is being read from "flat" memory (all sms from all
folders have unique numbers). It's sometimes emulated by Gammu. You 
can use it with all phones.

Other folders like 1, 2, etc. match folders in phone such as Inbox, Outbox, etc.
and each sms has unique number in his folder. Name of folders can
depend on your phone (the most often 1="Inbox", 2="Outbox", etc.).
This method is not supported by all phones (for example, not supported
by Nokia 3310, 5110, 6110). If work with your phone, use
\\fBgetsmsfolders\\fR to get folders list.
''' 
HELP['deletesms'] = '''Delete SMS from phone. See description for \\fBgetsms\\fR for info about
sms folders naming convention. 

Locations are numerated from 1.
'''
HELP['deleteallsms'] = '''Delete all SMS from specified SMS folder.
'''
HELP['getallsms'] = '''Get all SMS from phone. In some phones you will have also SMS templates
and info about locations used to save Picture Images. With each sms you
will see location. If you want to get such sms from phone alone, use
\\fBgammu getsms 0 location\\fR
'''
HELP['geteachsms'] = '''Similiary to \\fBgetallsms\\fR. Difference is, that
links all concatenated sms
'''
HELP['getsmsc'] = '''Get SMSC settings from SIM card. 

Locations are numerated from 1.
''' 
HELP['setsmsc'] = '''Set SMSC settings on SIM card. This keeps all SMSC configuration
intact, it just changes the SMSC number.

Locations are numerated from 1.
''' 
HELP['getsmsfolders'] = '''Get names for SMS folders in phone
'''
HELP['getphoneringtone'] = '''
Get one of "default" ringtones and saves into file
'''
HELP['playsavedringtone'] = '''
Play one of "built" ringtones. This option is available for DCT4 phones. For getting ringtones list use getringtoneslist.
'''
HELP['getringtoneslist'] = '''
Get list of predefined ringtones.
'''
HELP['getringtone'] = '''Get ringtone from phone in RTTL or BINARY format. 

Locations are numerated from 1.
'''
HELP['setringtone'] = '''Set ringtone in phone. When don't give location, it will be written
"with preview" (in phones supporting this feature like 61xx or 6210).
When use RTTL ringtones, give location and use \\fB\\-scale\\fR, there will be written
scale info with each note. It will avoid scale problems available during
editing ringtone in composer from phone menu (for example, in N33xx).

\\fITIP:\\fR when use ~ char in ringtone name, in some phones (like 
33xx) name will blink later in phone menus
'''
HELP['copyringtone'] = '''Copy source ringtone to destination.
'''
HELP['playringtone'] = '''Play aproximation of ringtone over phone buzzer. File can be in RTTL or BINARY (Nokia DCT3) format.
'''
HELP['getringtoneslist'] = ''''''
HELP['nokiacomposer'] = '''Show, how to enter RTTL ringtone in composer existing in many Nokia phones
(and how should it look like).
''' 
HELP['dialvoice'] = '''Make voice call from SIM card line set in phone.

\\fBshow|hide\\fR - optional parameter whether to disable call number indication.
''' 
HELP['maketerminatedcall'] = '''Make voice call from SIM card line set in phone which will 
be terminated after \\fBlength\\fR seconds.
''' 
HELP['answercall'] = '''Answer incoming call.
'''
HELP['cancelcall'] = '''Cancel incoming call
'''
HELP['splitcall'] = '''Splits call.
'''
HELP['switchcall'] = '''Switches call.
'''
HELP['transfercall'] = '''Transfers call.
'''
HELP['unholdcall'] = '''Unholds call.
'''
HELP['holdcall'] = '''Holds call.
'''
HELP['getussd'] = '''Retrieves USSD information - dials a service number and reads response.
'''
HELP['getspeeddial'] = '''Gets speed dial choices.
'''
HELP['canceldiverts'] = '''Cancel all existing call diverts.
'''
HELP['divert'] = '''Manage or display call diverts.

\\fBget|set\\fR - whether to get divert information or to set it.

\\fBall|busy|noans|outofreach\\fR - condition when apply divert

\\fBall|voice|fax|data\\fR - call type when apply divert

number - number where to divert

timeout - timeout when the diversion will happen

'''
HELP['conferencecall'] = '''Initiates a conference call.
'''
HELP['getcalendar'] = '''Retrieves selected calendar entries from phone.'''
HELP['getallcalendar'] = '''Retrieves all calendar entries from phone.'''
HELP['deletecalendar'] = '''Deletes selected calendar entries in phone. '''
HELP['gettodo'] = '''Retrieves selected todo entries from phone.'''
HELP['getalltodo'] = '''Retrieves all todo entries from phone.'''
HELP['deletetodo'] = '''Deletes selected todo entries in phone. '''
HELP['getcalendarsettings'] = '''Displays calendar settings like first day of
week or automatic deleting of old entries.
'''
HELP['getcalendarnotes'] = '''Get calendar notes from phone. In Nokia 3310 and 3330 they're named
"Reminders" and have some limitations (they depends on phone firmware version).
'''
HELP['getcategory'] = ''''''
HELP['getallcategies'] = ''''''
HELP['getwapbookmark'] = '''Get WAP bookmarks from phone. 

Locations are numerated from 1.
'''
HELP['deletewapbookmark'] = '''Delete WAP bookmarks from phone. 

Locations are numerated from 1.
'''
HELP['getwapsettings'] = '''Get WAP settings from phone. 

Locations are numerated from 1.
'''
HELP['getmmssettings'] = ''''''
HELP['getbitmap STARTUP'] = '''Get static startup logo from phone. Allow to save it in file.
'''
HELP['getbitmap CALLER'] = '''Get caller group logo from phone. Locations 1-5.
'''
HELP['getbitmap OPERATOR'] = '''Get operator logo (picture displayed instead of operator name) from phone.
''' 
HELP['getbitmap PICTURE'] = '''Get Picture Image from phone.
'''
HELP['getbitmap TEXT'] = '''Get startup text from phone.
'''
HELP['getbitmap DEALER'] = '''In some models it's possible to save dealer welcome note - text displayed
during enabling phone, which can't be edited from phone menu.  Here you can
get it.
'''
HELP['setbitmap STARTUP'] = '''Set startup logo in phone. It can be static (then you will have to give file
name) or one of predefined animated (only some phones like Nokia 3310 or 3330
supports it, use location 1, 2 or 3 for these).
'''
HELP['setbitmap WALLPAPER'] = '''Sets wallpaper in phone.''' 
HELP['setbitmap CALLER'] = '''Set caller logo.''' 
HELP['setbitmap OPERATOR'] = '''Set operator logo in phone. When won't give file and netcode, operator logo
will be removed from phone. When will give only filename, operator logo will
be displayed for your current GSM operator. When give additionally network
code, it will be displayed for this operator: \\fBgammu setbitmap OPERATOR file "260 02"\\fR
'''
HELP['setbitmap COLOUROPERATOR'] = '''Sets color operator logo in phone.''' 
HELP['setbitmap PICTURE'] = '''Sets picture image in phone.''' 
HELP['setbitmap TEXT'] = '''Sets startup text in phone.''' 
HELP['setbitmap DEALER'] = '''Sets welcome message configured by dealer, which usually can not be changed in phone menus.''' 
HELP['copybitmap'] = '''Allow to convert logos files to another. When give ONLY inputfile, output will
be written to stdout using ASCII art. When give output file and format, in
some file formats (like NLM) will be set indicator informing about logo type
to given.
'''
HELP['savefile CALENDAR'] = '''Allows to convert between various backup formats which gammu
supports for calendar events. The file type is guessed (for input file
guess is based on extension and file content, for output solely on 
extension).

For example if you want to convert single entry from gammu native 
backup to vCalendar, you need following command:

    gammu savefile CALENDAR output.vcs myCalendar.backup 260
'''
HELP['savefile TODO'] = '''Allows to convert between various backup formats which gammu
supports for todo events. The file type is guessed (for input file
guess is based on extension and file content, for output solely on 
extension).

For example if you want to convert single entry from gammu native 
backup to vCalendar, you need following command:

    gammu savefile CALENDAR output.vcs myCalendar.backup 260
'''
HELP['savefile VCARD10|VCARD21'] = '''Allows to convert between various backup formats which gammu
supports for phonebook events. The file type is guessed (for input file
guess is based on extension and file content, for output solely on 
extension).

For example if you want to convert single entry from gammu native 
backup to vCard, you need following command:

    gammu savefile CALENDAR output.vcf myPhonebook.backup ME 42
'''
HELP['savefile BOOKMARK'] = '''Converts backup format supported by
Gammu to vBookmark file.''' 
HELP['savesms TEXT'] = '''Take text from stdin (or commandline if \\-text 
specified) and save as text SMS into SIM/phone memory.

\\fB\\-flash\\fR - Class 0 SMS (should be displayed after receiving on recipients' phone display after receiving without entering Inbox)

\\fB\\-len len\\fR - specify, how many chars will be read. When use this
option and text will be longer than 1 SMS, will be split into more
linked SMS

\\fB\\-autolen len\\fR - specify, how many chars will be read. When use this
option and text will be longer than 1 SMS, will be split into more
linked SMS.Coding type (SMS default alphabet/Unicode) is set according
to input text

\\fB\\-enablevoice\\fR | \\fB\\-disablevoice\\fR | \\fB\\-enablefax \\fR |
\\fB\\-disablefax \\fR | \\fB\\-enableemail \\fR | \\fB\\-disableemail \\fR -
sms will set such indicators. Text will be cut to 1 sms.

\\fB\\-voidsms\\fR - many phones after receiving it won't display anything,
only beep, vibrate or turn on light. Text will be cut to 1 sms.

\\fB\\-unicode\\fR - SMS will be saved in Unicode format

\\fB\\-inputunicode\\fR - input text is in Unicode.

\\fB\\-text\\fR - get text from command line instead of stdin.

\\fB\\-textutf8\\fR - get text in UTF-8 from command line instead of stdin.

\\fB\\-16bit\\fR - Gammu uses SMS headers with 16-bit numbers for saving linking info in SMS (it means less chars available for user in each SMS)

\\fITIP:\\fR
You can create Unicode file using WordPad in Windows (during saving select
"Unicode Text Document" format). In Unix can use for example YUdit.

\\fB\\-replacemessages ID\\fR - \\fBID\\fR can be 1..7. When you will use option and
send more single SMS to one recipient with the same ID, each another SMS will
replace each previous with the same ID

\\fB\\-replacefile file\\fR  - when you want, you can make file in such format:
\\fBsrc_unicode_char1, dest_unicode_char1, src_unicode_char2, dest_unicode_char2\\fR
(everything in one line). After reading text for SMS from stdin there will
be made translation and each src char will be converted to dest char. In docs
there is example file (\\fIreplace.txt\\fR), which will change all "a" chars to "1"

\\fITIP:\\fR when use ~ char in sms text and \\fB\\-unicode\\fR option
(Unicode coding required), text of sms after ~ char will blink in some phones
(like N33xx)

\\fIExample:\\fR echo some_text | gammu savesms TEXT
'''
HELP['savesms RINGTONE'] = '''Read RTTL ringtone from file and save as SMS
into SIM/phone memory. Ringtone is saved in Nokia (Smart Messaging) format.

\\fB\\-long\\fR - ringtone is saved using Profile style. It can be longer (and saved
in 2 SMS), but decoded only by newer phones (like 33xx)

\\fB\\-scale\\fR - ringtone will have Scale info for each note. It will allow to edit
it correctly later in phone composer (for example, in 33xx)
'''
HELP['savesms OPERATOR'] = '''Save operator logo as sms in Nokia (Smart
Messaging) format - size 72x14 or 78x21 after using \\fB\\-biglogo\\fR, all in
two colors.

Please note, that it isn't designed for colour logos available for example in
DCT4/TIKU - you need to put bitmap file there inside phone using filesystem
commands.
'''
HELP['savesms CALLER'] = '''Save caller logo as sms in Nokia (Smart Messaging)
format - size 72x14, two colors.

Please note, that it isn't designed for colour logos available for example in
DCT4/TIKU - you need to put bitmap file there inside phone using filesystem
commands.
'''
HELP['savesms PICTURE'] = '''
Read bitmap from 2 colors file (bmp, nlm, nsl, ngg, nol, wbmp, etc.), format
into bitmap in Smart Messaging (72x28, 2 colors, called often Picture Image
and saved with text) or Alcatel format and send/save over SMS.
'''
HELP['savesms ANIMATION'] = '''Save an animation as a SMS. You need to give
number of frames and picture for each frame. Each picture can be in any
picture format which Gammu supports (B/W bmp, gif, wbmp, nol, nlm...).
'''
HELP['savesms MMSINDICATOR'] = '''
Saves a message with MMS indication. The recipient phone will then download
MMS from given URL and display it.

Please note that you should provide valid smil data on that URL.
'''
HELP['savesms BOOKMARK'] = '''Read WAP bookmark from file created by \\fBbackup\\fR option and saves in
Nokia format as SMS
'''
HELP['savesms WAPSETTINGS'] = '''Read WAP settings from file created by \\fBbackup\\fR option and saves in Nokia format as SMS
'''
HELP['savesms MMSSETTINGS'] = '''Saves a message with MMS configuration. The
configuration will be read from Gammu backup file from given location.''' 
HELP['savesms CALENDAR'] = '''Read calendar note from file created by \\fBbackup\\fR option and saves in
VCALENDAR 1.0 format as SMS. The location identifies position of calendar item 
to be read in backup file (usually 1, but can be useful in case the backup contains 
more items).
'''
HELP['savesms TODO'] = '''Saves a message with a todo entry. The content will
be read from any backup format which Gammu supports and from given location.'''
HELP['savesms VCARD10|VCARD21'] = '''Read phonebook entry from file created by \\fBbackup\\fR option and saves in
VCARD 1.0 (only name and default number) or VCARD 2.1 (all entry details with
all numbers, text and name) format as SMS. The location identifies position of contact item 
to be read in backup file (usually 1, but can be useful in case the backup contains 
more items).
'''
HELP['savesms PROFILE'] = '''
Read ringtone (RTTL) format, bitmap (Picture Image size) and name, format into
Smart Messaging profile and send/save as SMS. Please note, that this format is
abandomed by Nokia and supported by some (older) devices only like Nokia 3310.
'''
HELP['savesms SMSTEMPLATE'] = '''Saves a SMS template (for Alcatel phones).
'''
HELP['savesms WAPINDICATOR'] = '''Saves a SMS with a WAP indication for given
URL and title.
'''
HELP['savesms EMS'] = '''
Saves EMS sequence. All parameters after \\fB\\-unread\\fR (like \\fB\\-defsound\\fR) can be used few times.

\\fB\\-text\\fR - adds text

\\fB\\-unicodefiletext\\fR - adds text from Unicode file

\\fB\\-defanimation\\fR - adds default animation with ID specified by user.ID for different phones are different.

\\fB\\-animation\\fR - adds "frames" frames read from file1, file2, etc.

\\fB\\-defsound\\fR - adds default sound with ID specified by user. ID for different phones are different.

\\fB\\-tone10\\fR - adds IMelody version 1.0 read from RTTL or other compatible file

\\fB\\-tone10long\\fR - IMelody version 1.0 saved in one of few SMS with UPI. Phones compatible with UPI (like SonyEricsson phones) will read such ringtone as one

\\fB\\-tone12\\fR - adds IMelody version 1.2 read from RTTL or other compatible file

\\fB\\-tone12long\\fR - IMelody version 1.2 saved in one of few SMS with UPI. Phones compatible with UPI (like SonyEricsson phones) will read such ringtone as one

\\fB\\-toneSE\\fR - adds IMelody in "short" form supported by SonyEricsson phones

\\fB\\-toneSElong\\fR - add SonyEricsson IMelody saved in one or few SMS with UPI

\\fB\\-variablebitmap\\fR - bitmap in any size saved in one SMS

\\fB\\-variablebitmaplong\\fR - bitmap with maximal size 96x128 saved in one or few sms

\\fB\\-fixedbitmap\\fR - bitmap 16x16 or 32x32

\\fB\\-protected\\fR - all ringtones and bitmaps after this parameter (excluding default ringtones and logos) will be "protected" (in phones compatible with ODI like SonyEricsson products it won't be possible to forward them from phone menu)

\\fB\\-16bit\\fR - Gammu uses SMS headers with 16-bit numbers for saving linking info in SMS (it means less chars available for user in each SMS)

\\fB\\-format\\fR lcrasbiut - last text will be formatted. You can use combinations of chars:
    l - left aligned
    c - centered
    r - right aligned
    a - large font
    s - small font
    b - bold font
    i - italic font
    u - underlined font
    t - strikethrough font

\\fIExample:\\fR gammu savesms EMS \\-text "Greetings" \\-defsound 1 \\-text "from Gammu" \\-tone10 axelf.txt \\-animation 2 file1.bmp file2.bmp

will create EMS sequence with text "Greetings" and default sound 1 and text "from Gammu" and ringtone axelf.txt and 2 frame animation read from (1'st frame) file1.bmp and (2'nd frame) file2.bmp

\\fIExample:\\fR gammu savesms EMS \\-protected 2 \\-variablebitmaplong ala.bmp \\-toneSElong axelf.txt \\-toneSE ring.txt

ala.bmp and axelf.txt will be "protected"
'''
HELP['displaysms'] = '''
Displays PDU data of encoded SMS messages. It accepts same parameters and 
behaves same like sendsms.
''' 
HELP['nokiagett9'] = '''This option should display T9 dictionary content from
DCT4 phones.
'''
HELP['nokiagetoperatorname'] = '''6110.c phones have place for name for one GSM network (of course, with flashing it's
possible to change all names, but Gammu is not flasher ;\\-)). You can get this
name using this option.
''' 
HELP['nokiasetoperatorname'] = ''''''
HELP['nokiadisplayoutput'] = ''''''
HELP['nokiasetvibralevel'] = '''Set vibra power to "level" (given in percent)
'''
HELP['nokiagetvoicerecord'] = '''
Get voice record from location and save to WAV file. File is
coded using GSM 6.10 codec (available for example in win32). Name
of file is like name of voice record in phone.

Created WAV files require GSM 6.10 codec to be played. In Win XP it's included
by Microsoft. If you deleted it by accident in this operating system, make such
steps:

1. Control Panel
.br
2. Add hardware
.br
3. click Next
.br
4. select "Yes. I have already connected the hardware"
.br
5. select "Add a new hardware device"
.br
6. select "Install the hardware that I manually select from a list"
.br
7. select "Sound, video and game controllers"
.br
8. select "Audio codecs"
.br
9.  select "windows\\\\system32" directory and file "mmdriver.inf"
.br
10. if You will be asked for file msgsm32.acm, it should unpacked from Windows CD
.br
11. now You can be asked if want to install unsigned driver (YES), about select codec configuration (select what you want) and rebotting PC (make it)
'''
HELP['nokiasecuritycode'] = '''Get/reset to "12345" security code
''' 
HELP['nokiatests'] = '''Make tests for Nokia DCT3 phones

\\fINOTE:\\fR EEPROM test can show error, when your phone has EEPROM in flash
(like in 82xx/7110/62xx/33xx). The same Clock test will show error
when phone doesn't have internal battery for clock (like 3xxx)
...and for DCT4 (work in progress)
'''
HELP['nokiasetphonemenus'] = '''Enable all (?) possible menus for DCT3 Nokia phones:

1. ALS (Alternative Line Service) option menu
.br
2. vibra menu for 3210
.br
3. 3315 features in 3310 5.45 and higher
.br
4. two additional games (React and Logic) for 3210 5\\.31 and higher
.br
5. WellMate menu for 6150
.br
6. NetMonitor

and for DCT4:

1. ALS (Alternative Line Service) option menu
.br
2. Bluetooth, WAP bookmarks and settings menu, ... (6310i)
.br
3. GPRS Always Online
.br
 ...
'''
HELP['nokiaselftests'] = '''
Perform tests for Nokia DCT3 phones.

Note: EEPROM test can show an error when your phone has an EEPROM in 
flash (like 82xx/7110/62xx/33xx). The clock test will show an error 
when the phone doesn?t have an internal battery for the clock (like
3xxx).
'''
HELP['nokianetmonitor'] = '''Takes output or set netmonitor for Nokia DCT3 phones.

\\fITIP:\\fR For more info about this option, please visit
\\fIhttp://www.mwiacek.com\\fR and read netmonitor manual.

\\fITIP:\\fR test \\fB243\\fR enables all tests (after using command
\\fBgammu nokianetmonitor 243\\fR in some phones like 6210 or 9210 have to
reboot them to see netmonitor menu)
''' 
HELP['nokianetmonitor36'] = '''Reset counters from netmonitor test 36 in Nokia DCT3 phones.

\\fITIP:\\fR For more info about this option, please visit
\\fIhttp://www.mwiacek.com\\fR and read netmonitor manual.
'''
HELP['siemenssatnetmon'] = ''''''
HELP['siemensnetmonitor'] = ''''''
HELP['siemensnetmonact'] = '''
Enables network monitor in Siemens phone. Currently known values for type
are 1 for full and 2 for simple mode.''' 
HELP['backup'] = '''Backup your phone to file. It's possible to backup (depends on phone and backup format):

* phonebook from SIM and phone memory
.br
* calendar notes
.br
* SMSC settings
.br
* operator logo
.br
* startup (static) logo or startup text
.br
* WAP bookmarks
.br
* WAP settings
.br
* caller logos and groups
.br
* user ringtones
.br

There are various backup formats supported and the backup format is guessed
based on file extension:

* .lmb - Nokia backup, supports contacts, caller logos and startup logo.
.br
* .vcs - vCalendar, supports calendar and todo.
.br
* .vcf - vCard, supports contacts.
.br
* .ldif - LDAP import, supports contacts.
.br
* .ics - iCalendar, supports calendar and todo.
.br
* Any other extension is Gammu backup file and it supports all data mentioned above.

See \\fBEXAMPLE\\fR section for some hints on manipulating Gammu backup format.

'''
HELP['backupsms'] = '''Stores all SMSes from phone to file. 

Use \\-yes for answering yes to all questions (backup all messages and 
delete them from phone), or \\-all to just backup all folders while keeping
messages in phone.
''' 
HELP['addsms'] = '''Adds SMSes from file (format like backupsms uses) to
selected folder in phone.'''
HELP['restoresms'] = '''Restores SMSes from file (format like backupsms uses) to
selected folder in phone. Please note that this overwrites existing
messages in phone (if it supports it).'''
HELP['restore'] = '''Restore settings written in file created using \\fBbackup\\fR option. 

Please note that restoring deletes all current content in phone. If you
want only to add entries to phone, use addnew.

In some phones restoring calendar notes will not show error, but won't
be done, when phone doesn't have set clock inside.
'''
HELP['addnew'] = '''Adds data written in file created using \\fBbackup option\\fR. All things
backup'ed by \\fBbackup\\fR can be restored (when made backup to Gammu text
file).

Please note that this adds all content of backup file to phone and
does not care about current data in the phone (no duplicates are 
detected).

Use \\-yes parameter to answer yes to all questions (you want to automatically 
restore all data).

Use \\-memory parameter to force usage of defined memory type for storing entries 
regardless what backu format says.
'''
HELP['clearall'] = '''Deletes all private data from the phone.
''' 
HELP['decodesniff'] = '''Option available only, if Gammu was compiled with debug. Allows to decode
sniffs. See \\fI/docs/develop/develop.txt\\fR for more details.
''' 
HELP['decodebinarydump'] = '''Decodes a dump made by Gammu with 
\\fBlogformat\\fR se to \\fBbinary\\fR (see \\fIREADME\\fR for
info about this method of reporting bugs).

This option is available only if Gammu was compiled with debuging options.

''' 
HELP['getallnotes'] = '''Reads all notes from the phone.

Note: Not all phones supports this function, especially most Sony Ericsson 
phones even if they have notes inside phone.
'''
HELP['searchphone'] = '''Attempts to search for a connected phone. Please note
that this can take a very long time, but in case you have no clue how to
configure phone connection, this is a convenient way to find working setup for
Gammu.'''
HELP['batch'] = '''Starts Gammu in a batch mode. In this mode you can issue
several commands each on one line. Lines starting with # are treated as a
comments.

By default, commands are read from standard input, but you can optionally
specify a file from where they would be read (special case - means standard
input).
'''

# Generate help for savesms
for k in HELP.keys():
    if k[:7] == 'savesms':
        send_key = 'sendsms' + k[7:]
        HELP[send_key] = SMS_SEND_HELP % k 
        HELP[send_key] += SMS_COMMON_HELP
        HELP[k] += SMS_COMMON_HELP

SECTION_HELP = {}
SECTION_HELP['sms'] = '''
Sending messages might look a bit complicated on first attempt to use.
But be patient, the command line has been written in order to allow
almost every usage. See EXAMPLE section for some hints on usage.

There is also an option to use gammu-smsd(1) when you want to send or 
receive more messages and process them automatically.

.TP
\\fBCommon parameters for sendsms and savesms\\fR

\\fB\\-smscset number\\fR - SMSC will be taken from set \\fBnumber\\fR. Default set: 1

\\fB\\-smscnumber number\\fR - SMSC number

\\fB\\-reply\\fR - reply SMSC is set

\\fB\\-maxnum number\\fR - Limit maximal number of messages which will be
created. If there are more messages, Gammu will terminate with failure.

\\fB\\-folder number\\fR - save to specified folder. 

Folders are numerated from 1.

The most often folder 1 = "Inbox", 2 = "Outbox",etc. Use \\fBgetsmsfolders\\fR to get folder list.

\\fB\\-unread\\fR - makes message unread. In some phones (like 6210) you won't see 
unread sms envelope after saving such sms. In some phones with internal 
SMS memory (like 6210) after using it with folder 1 SIM SMS memory will be used

\\fB\\-read\\fR - makes message read. In some phones with internal
SMS memory (like 6210) after using it with folder 1 SIM SMS memory will be used

\\fB\\-unsent\\fR - makes message unsent

\\fB\\-sent\\fR - makes message sent

\\fB\\-sender number\\fR - set sender number

\\fB\\-smsname name\\fR - set message name

\\fB\\-sender number\\fR - set sender number (default: "Gammu")

\\fB\\-report\\fR - request delivery report for message

\\fB\\-validity HOUR|6HOURS|DAY|3DAYS|WEEK|MAX\\fR - sets how long will be the
message valid (SMSC will the discard the message after this time if it could
not deliver it).

\\fB\\-save\\fR - will also save message which is being sent

.TP
\\fBIntroduction to SMS formats\\fR

Gammu has support for many SMS formats like:

\\fBNokia Smart Messaging\\fR (used for monochromatic picture images, downloadable profiles, monochromatic operator logos, monochromatic caller logos and monophonic ringtones)

\\fBLinked SMS\\fR (both with 8 and 16-bit identification numbers in headers)

\\fBEMS\\fR (this is SMS format used for saving monochromatic images, monophonic ringtones, animations, text formatting and others)

\\fBMMS notifications\\fR

\\fBAlcatel logo messages\\fR


You need to ensure that the target phone supports message type you want to
send. Otherwise the phone will not be able to display it or will even crash,
because firmware of phone did not expect this possibility.

.TP
\\fBEncoding chars in SMS text\\fR

Text in SMS can be coded using two ways:

with \\fBGSM Default Alphabet\\fR - in single SMS you can have maximally 160 chars (Gammu doesn't support compressing such texts according to GSM standards, but it isn't big limit, because there are no phones supporting them), but they're from limited set:

  * all Latin small and large

  * all digits

  * some Greek

  * some other national

  * some symbols like  @ ! " # & / ( ) % * + = - , . : ; < > ?

  * few others

with \\fBUnicode\\fR - in single SMS you can save at most 70 chars, but these can be
any chars including all national and special ones. Please note, that some
older phones might have problems displaying such message.

Gammu tries to do the best to handle non ASCII characters in your message.
Everything is internally handled in Unicode (the input is converted depending
on your locales configuration) and in case message uses Unicode the text will
be given as such to the message. 

Should the message be sent in GSM Default Alphabet, Gammu will try to convert
all characters to keep message readable. Gammu does support multi byte
encoding for some characters in GSM Default Alphabet (it is needed for ^ { }
\\\\ [ ] ~ |). The characters which are not present in GSM Default Alphabet
are transliterated to closest ASCII equivalent (accents are removed).
Remaining not known characters are replaced by question mark.
'''
SECTION_HELP['filesystem'] = '''
Gammu allows to access phones using native protocol (Nokias) or OBEX. Your
phone can also support usb storage, which is handled on the operating system
level and Gammu does not use that.
'''
SECTION_HELP['ringtone'] = '''
Ringtones are mostly supported only for older phones. For recent phones you
usually just upload them to some folder in phone filesystem.

There are recognized various file formats by options described below: rttl,
binary format created for Gammu, mid (saving), re (reading), ott, communicator,
ringtones format found in fkn.pl, wav (saving), ime/imy (saving), rng, mmf (for
Samsung).

'''
SECTION_HELP['calendar'] = '''
In Nokia 3310, 3315 and 3330 these are named "Reminders" and have some limitations (depending on phone firmware version).
'''
SECTION_HELP['logo'] = '''
These options are mainly (there are few expections) for monochromatic logos and
images available in older phones. Recognized file formats: xpm (only saving),
2-colors bmp, nlm, nsl, ngg, nol, wbmp, gif (for Samsung).

In new models all bitmaps are saved in filesystem and should go into filesystem section
'''

# Code

import os
import re

SECTION_MATCHER = re.compile(' *([^ ]+) - (.+)')
COMMAND_MATCHER = re.compile('^([^ \n]+) (.+)')
COMMAND_SUBCOMMAND_MATCHER = re.compile('^([^ \n]+) ([A-Z][A-Za-z0-9|]+)( (.*)|)')
COMMAND_MATCHER_NOPARAM = re.compile('^([^ \n]+)')

def read_errors():
    pipe = os.popen('LANG=C %s -m' % ERROR_LIST_PATH)
    data = pipe.read()
    pipe.close()
    return data

def read_help(section):
    pipe = os.popen('LANG=C %s help %s' % (BIN_PATH, section))
    data = pipe.readlines()
    pipe.close()
    if data[0].find('No configuration file found!') != -1:
        del data[0]
    return data

def parse_sections(lines):
    sections = []
    section_data = {}
    for line in lines:
        match = SECTION_MATCHER.match(line)
        if match is None:
            continue
        section = match.groups()[0]
        sections.append(section)
        section_data[section] = match.groups()[1]
    return sections, section_data

def parse_section_help(lines):
    result = {}
    for line in lines:
        match = COMMAND_SUBCOMMAND_MATCHER.match(line)
        if match is None:
            match = COMMAND_MATCHER.match(line)
            if match is None:
                match = COMMAND_MATCHER_NOPARAM.match(line)
                command = match.groups()[0]
                options = ''
            else:
                command = match.groups()[0]
                options = match.groups()[1]
        else:
            command = '%s %s' % (match.groups()[0], match.groups()[1])
            if match.groups()[3] is None:
                options = ''
            else:
                options = match.groups()[3]
        result[command] = options
    return result

def get_command_help(command):
    try:
        ret = HELP[command]
        if ret == '':
            raise KeyError()
        return ret
    except KeyError:
        try:
            maincommand = command.split(' ')[0]
            ret = HELP[maincommand]
            if ret == '':
                raise KeyError()
            print 'Fallback to "%s" from "%s"' % (maincommand, command)
            return ret
        except:
            print 'No help for "%s"' % command
            return ''

def write_section(output, name):
    output.write(SECTION % name)

def write_subsection(output, name):
    output.write(SUBSECTION % name)

def write_para(output, text):
    output.write(PARAGRAPH % text)

def write_command(output, name, params, help):
    if params == '':
        output.write(COMMAND_NOPARAM % (name, help))
    else: 
        output.write(COMMAND % (name, 
                params.replace('][', '] ['), 
                help))

def format_man_page(output, data):
    keys = data.keys()
    keys.sort()
    for command in keys:
        write_command(output, command, data[command].replace('-', '\\-'), get_command_help(command))

def main():
    text = read_help('')
    result = re.match('\[Gammu version ([0-9.]*) built [0-9:]* on (.*) using.*\]', text[0])
    build_date = result.groups()[1]
    version = result.groups()[0]
    syntax = text[2]

    syntax_help = '.br\n'.join(text[4:9]).replace('nothing|text|textall|textalldate|binary|errors', 'see gammurc(5) for possible values')
    commands_help = text[10]

    output = file(OUT_PATH, 'w')
    output.write(HEADER % {'version' : version, 'date' : build_date})

    write_section(output, 'NAME')
    output.write(NAME)

    write_section(output, 'SYNOPSIS')
    write_para(output, syntax.replace('[', '[\\fI').replace(']', '\\fP]'))

    write_section(output, 'DESCRIPTION')

    write_para(output, DESCRIPTION)

    write_section(output, 'OPTIONS')

    write_para(output, syntax_help.replace('-', '\\-'))

    write_subsection(output, 'Commands')
    write_para(output, commands_help.replace('-', '\\-'))

    sections, section_data = parse_sections(text[12:])
    for section in sections:
        section_text = read_help(section)
        write_subsection(output, section_data[section])
        try:
            write_para(output, SECTION_HELP[section])
        except KeyError:
            pass
        data = parse_section_help(section_text[4:])
        format_man_page(output, data)

    write_section(output, 'FILES')
    output.write(FILES)

    write_section(output, 'RETURN VALUES')
    output.write(RETURN_VALUES)
    output.write(read_errors().replace('-', '\\-'))

    write_section(output, 'EXAMPLE')
    output.write(EXAMPLE)

    write_section(output, 'COPYRIGHT')
    output.write(COPYRIGHT)

    write_section(output, 'REPORTING BUGS')
    output.write(BUGS)

    write_section(output, 'AUTHOR')
    output.write(AUTHOR)

    write_section(output, 'SEE ALSO')
    output.write(SEE_ALSO)

    output.close()

if __name__ == '__main__':
    main()
