#!/usr/bin/python3

import sys
import re

sections = ['intro', 'usage', 'examples', 'checkoptions', 'createoptions',
            'copyoptions', 'displayoptions', 'modoptions',
            'addrmoptions', 'diffoptions', 'miscoptions',
            'helpoptions', 'status' ]

def prettyPrint( tlist, killcolon = False, markupcolon = False ):
    for line in tlist:
        line = re.sub("'", '"', line)
        if killcolon:
            parts=re.split(':',line)
            line = '.PP\n' + '\\fB' + parts[0].strip() + '\\fR ' + ' '.join(parts[1:]).strip()
        if markupcolon and line.find(':') >= 0:
            line = '\\fI' + line + '\\fR'
        if not line:
            print('.PP')
            continue
        elif line.startswith('- ') or line.startswith('o '):
            line = line[2:]
            print('.IP')
        elif line.startswith('-'):
            parts = re.split(' ', line)
            line = '\\fI' + parts[0] + '\\fR' + ' ' + ' '.join(parts[1:]) + '\n'
        elif line.startswith('one can'):
            print(line[ :line.find('-')].strip())
            print('.IP')
            line = line[ line.find('-')+1:].strip()
        elif line.startswith('Note:'):
            print('\\fBNote:\\fR', line[6:])
            continue
        print(line)

if __name__ == "__main__":
    sec_counter = 0

    # initialize section dict
    info = {}
    for i in sections:
        info[i] = []

    # fill section dict
    #print "Section:", sections[sec_counter]
    for line in sys.stdin:
        # strip useless stuff
        line = line.strip()
        if line.startswith('------'):
            sec_counter += 1
            #print 'Section:', sections[sec_counter]
        info[sections[sec_counter]].append( line )

    # transform section dict into a nice manpage
    print('.TH "NIFTI_TOOL" "1" "" "Michael Hanke" ""')
    print('.SH NAME')
    print('nifti_tool - multipurpose manipulation tool for NIfTI files')

    print('.SH SYNOPSIS')
    prettyPrint( info['usage'][4:], killcolon=True)
    print('.BR')

    print('.SH DESCRIPTION')
    prettyPrint( ['This tool can'] + info['intro'][2:] )

    print('.SH OPTIONS')
    print('\\fBCheck options\\fB\n.BR\n')
    prettyPrint( info['checkoptions'][4:])
    print('\\fBCreate options\\fB\n.BR\n')
    prettyPrint( info['createoptions'][4:])
    print('\\fBCopy options\\fB\n.BR\n')
    prettyPrint( info['copyoptions'][4:])
    print('\\fBDisplay options\\fB\n.BR\n')
    prettyPrint( info['displayoptions'][4:])
    print('\\fBModification options\\fB\n.BR\n')
    prettyPrint( info['modoptions'][4:])
    print('\\fBAdd, remove options\\fB\n.BR\n')
    prettyPrint( info['addrmoptions'][4:])
    print('\\fBDifference options\\fB\n.BR\n')
    prettyPrint( info['diffoptions'][4:])
    print('\\fBMiscellaneous options\\fB\n.BR\n')
    prettyPrint( info['miscoptions'][4:])
    print('\\fBHelp options\\fB\n.BR\n')
    prettyPrint( info['helpoptions'][4:])

    print('.SH EXAMPLES')
    prettyPrint( info['examples'][4:], markupcolon=True)

    print("""\
.SH "SEE ALSO"
.BR libnifti (1),
.BR nifti1_test (1),
.BR nifti_stats (1).
.PP
Homepage:
.I http://niftilib.sourceforge.net

.SH "AUTHOR"
The \\fBNIfTI\\fR libraries were written by the NIfTI Data Format Working Group
(DFWG,
.I  http://nifti.nimh.nih.gov/
).
.PP
This manual page was generated by a custom script, written by Michael Hanke
<michael.hanke@gmail.com> (available within the Debian package) from the help
output of the nifti_tool binary.'
""")
