#!/usr/bin/env python
"""
make a table of contents in HTML from a PostScript source
"""
import os, sys, string
filename = sys.argv[1]
if not os.path.isfile("%s.ps" % filename):
    print "file %s.ps not found" % filename
    sys.exit(1)
    
os.system("pstotext %s.ps > %s.txt" % (filename,filename))
f = open("%s.txt" % filename, 'r')
lines = f.readlines()
f.close()

html = open("%s.html" % filename, 'w')
html.write("""
<table>
""")

for line in lines:
    if line.find("Table of") > -1:  # skip "Table of contents" lines
        continue
    s = line.split()
    # remove the dots:
    news = []
    for item in s:
        if item != '.': news.append(item)
    if len(news) > 1:
        chapter = news[0]
        page = news[-1]
        title = string.join(news[1:-1])
        if chapter.find('.') == -1:
            chapter = "<b>%s</b>" % chapter  # set chapter numbers in boldface
            html.write("<tr><td></td></tr>\n")
        html.write("<tr><td align=left>%s</td><td align=left>%s</td><td align=right>%s</td></tr>\n" % (chapter, title, page))
html.write("\n</table>")
html.close()


        
