'''
Converts a text file into a C function called manpage that prints
the indicated text to a stream.

Copyright (C) 2002 GDS Software

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.

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., 59 Temple Place, Suite 330, Boston,
MA  02111-1307  USA

See http://www.gnu.org/licenses/licenses.html for more details.
'''

import sys, string
__version__ = "$Id: man2c.py,v 1.4 2002/08/21 17:37:39 donp Exp $"

def GetLines():
    ifp = open(sys.argv[1])
    lines = ifp.readlines()
    ifp.close()
    TransformLines(lines)
    return lines

def PrintHeader():
    print '''/* Automatically generated by man2c.py */\n
#include <stdio.h>

void manpage(FILE *ofp)
{
    fprintf(ofp, 
'''

def PrintLines(lines):
    for line in lines:
        print line

def PrintTrailer():
    print "    );"
    print "\n}\n"

def TransformLines(lines):
    '''Escape the characters so that they printf OK.  This includes
    double quotes, backslashes, tabs, and % characters.'''
    for ix in xrange(len(lines)):
        line = string.rstrip(lines[ix])
        line = string.replace(line, "\\", r"\\")
        line = string.replace(line, "\"", r"\"")
        line = string.replace(line, "%",   "%%")
        line = string.replace(line, "\t", r"\t")
        line = "\"" + line + "\\n\""
        lines[ix] = line

def main():
    if (len(sys.argv) != 2):
        sys.stderr.write("Usage:  man2c file\n")
        sys.exit(1)
    lines = GetLines()
    PrintHeader()
    PrintLines(lines)
    PrintTrailer()

main()
