#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import os.path
import sys
import fnmatch
import glob
import traceback

exps = [(r"\\bigskip", ""),
        (r"\\ldots", "&hellip;"),  
        #(r"[\r\n]{2,}",r"<br><br>"),
        (r"([\s\S]*?)[\r\n]{2,}", r"<p>\1</p>"),  
        (r"\\centering", ""),
        (r"\\par", ""),
        (r"\\degree", "&deg;"),
        (r"\\noindent", ""),
        (r"\\begin\{center\}", ""),
        (r"\\end\{center\}", ""),
        (r"\\small", ""), 
        (r"\\index\{.*?\}", ""),
        (r"\\pagestyle\{.*?\}",r""),
        (r"\\%", "%"),
        (r"\\_", "_"),
        (r"\\begin\{intro\}([\s\S]*?)\\end\{intro\}", r"<p><i>\1</i></p>"), 
        (r"\\begin\{verbatim\}([\s\S]*?)\\end\{verbatim\}", r"<code>\1</code>"), 
        (r"\\footnote\{[\s\S]*?\}", ""),
        (r"\\begin\{itemize\}", "<ul>"),
        (r"\\end\{itemize\}", "</ul>"),
        (r"\\begin\{enumerate\}", "<ol>"),
        (r"\\end\{enumerate\}", "</ol>"),
        (r"\\item", "<li>"),
        (r"\\emph\{(.*?)\}", r"<i>\1</i>"),
        (r"\\texttt\{(.*?)\}", r"<tt>\1</tt>"),
        (r"\\chapter.*?\{(.*?)\}", ""),
        (r"\\section.*?\{(.*?)\}", r'<h2 id="\1">\1</h2>'),
        (r"\\subsection.*?\{(.*?)\}", r'<h3 id="\1">\1</h3>'),
        (r"\\subsubsection.*?\{(.*?)\}", r'<h4 id="\1">\1</h4>'),
        (r"\\begin\{figure\}.*?\n", ""),
        (r"\\end\{figure\}", ""),
        (r"\\caption\{(.*?)\}", r"<i>\1</i>"),
        (r"(\\label\{Fig:.*?\})", r"$$\1$$"),
        (r"\\includegraphics.*?\{(.*?)\}", r"<img src='\1'><br>"),
        (r"---", "&#8212;"),
        (">>", "&raquo;"),
        ("<<", "&laquo;"),
        (r"\\vspace\{.*?\}", "<br><br><br>"),
        #(r"\\.*?\{.*?\}", ""),
        (r"(<br><br>){2,}",r"<br><br>"), 
        (r"><br><br>",r"><br>"),
        ]


def template():
    path = "template.html"
    with open(path) as f:
        s = f.read()
    return s

labelrefs = {}

def convertFile(path): 
    name = os.path.splitext(os.path.basename(path))[0]
    with open(path) as f:
        s = f.read()
    p = re.compile(r"\\chapter.*?\{(.*?)\}")
    title = p.findall(s)[0]
    p = re.compile(r"\\chapterauthor\{(.*?)\}")
    authors = p.findall(s)
    p = re.compile(r"\\cite\{([\S]*?)\}")
    cites = p.findall(s) 
    for cite in cites:
        rep = "".join(['[<a href="bib.htm#%s">%s</a>]' % (c,c) for c in cite.split(",")])
        s = s.replace(r"\cite{%s}" % cite, rep)
    p = re.compile(r"\\label\{([^:]*?)\}")
    labels = p.findall(s)
    global labelrefs
    for label in labels:
        labelrefs[label] = name
    s = p.sub(r'<a name="\1"></a>', s) 
    for exp, replace in exps:
        p = re.compile(exp)
        s = p.sub(replace, s)
  
    s = template().replace("[BODY]", s).replace("[TITLE]", title)
    if authors:
        s = s.replace("[AUTHOR]", "<p><i>%s</i></p>" % authors[0])
    else:
        s = s.replace("[AUTHOR]", "")
    with open(os.path.join("build", name + ".html"), "w") as f:
        f.write(s)

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename
                
if __name__ == '__main__':
    i = 0
    for f in find_files('../latex', '*.tex'):
        try:
            convertFile(f)
        except Exception, e:
            traceback.print_exc()
            pass 
    for path in  glob.glob("build/*.html"):
        with open(path) as f:
            s = f.read()
        p = re.compile(r"\\ref\{([^:]*?)\}")
        refs = p.findall(s)
        for ref in refs:
            try:
                s = s.replace(r"\ref{%s}" % ref, '<a href="%s.html#%s">%s</a>' % (labelrefs[ref], ref, ref))
            except KeyError:
                print ref
        with open(path, "w") as f:
            f.write(s)
    