import sys
import re
import os

argv = sys.argv

infile  = None
outfile = None
if len(argv) >= 2:
    infile = argv[1]


def escape(t):
    """HTML-escape the text in `t`."""
    return (t
#        .replace("&", "&amp;")
#        .replace("<", "&lt;").replace(">", "&gt;")
#        .replace("'", "&#39;").replace('"', "&quot;")
        .replace(" ", "&nbsp;")
        )

outfile = re.sub(r'\.py', '.html', infile)
jpgfile = re.sub(r'\.py', '.jpg', infile)
print("in file  :", infile)
print("out file :", outfile)
print("jpeg file:", jpgfile)

fin = open(infile, 'r', encoding='utf-8')
lines = fin.readlines()
fin.close()

fout = open(outfile, 'w')

IsComment = False
title = 'No title'
for i in range(len(lines)):
    line = lines[i]
    line = line.rstrip()
    ret = re.search(r"^(.*?)('''|\"\"\")(.*)$", line)
    if ret:
        title = ''
        for j in range(i+1, len(lines)):
            if re.search(r"('''|\"\"\")", lines[j]):
                break
            title += lines[j]

        title = re.sub(r'\n', r'<br>\n', title.rstrip())
        break

print("Title:", title)

fout.write("<html>\n" + "<head>\n")
fout.write("<title>{}</title>\n".format(title))
fout.write("</head>\n" + "<body><tt>\n")

fout.write('\n')
fout.write('<b><font color="blue">{}</font></b><p>\n'.format(title))
fout.write('<b><font color="blue"><a href="{}">{}</a></font></b><p>\n'.format(infile, infile))
fout.write('\n')

for i in range(len(lines)):
    line = lines[i]
    line = line.rstrip()
    
    ret = re.search(r"^(\s*)(.*)$", line)
    if ret:
        spc  = ret[1]
        line = ret[2]
        spc  = re.sub(r' ', '&nbsp;', spc)
    else:
        spc = ''

    ret = re.search(r"^(.*?)(''')(.*)$", line)
    if ret:
        if not IsComment:
            IsComment = True
            line = ret[1] + '{font_red_start}' + ret[2] + ret[3]
        else:
            IsComment = True
            line = ret[1] + ret[2] + '{font_red_end}' + ret[3]

    ret = re.search(r'^(.*?)(""")(.*)$', line)
    if ret:
        if not IsComment:
            IsComment = True
            line = ret[1] + '{font_red_start}' + ret[2] + ret[3]
        else:
            IsComment = True
            line = ret[1] + ret[2] + '{font_red_end}' + ret[3]

    line = re.sub(r'^(.*?)(#)(.*)$', r'\1{font_red_start}\2\3{font_red_end}', line)

    line = re.sub(r'{font_red_start}', '<font color="red">', line)
    line = re.sub(r'{font_red_end}', '</font>', line)

#    print(spc + line)
    fout.write(spc + line + "<br>\n")

fout.write("</tt>\n")

fout.write('<a href="{}">\n<img border="0" src="{}" width="300">\n</a>\n'
        .format(jpgfile, jpgfile))


fout.write("</body>\n")

fout.close()

