#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
asttex.py [opts] grammar in.tex*

  a LaTeX preprocessor.  Scans in.tex files for occurrences of $$ ... $$,
  parses them using the same syntax rules obeyed by astpp.py, and 
  then emits a new out.tex file with each $$ ... $$ section replaced with a
  standard .tex syntax.

  Requires mathpartir:
      http://pauillac.inria.fr/~remy/latex/mathpartir.sty
"""

import sys, codecs, re
from astparse import grparse, parse_prod
from astast import latex
import astutil

# ______________________________________________________________________
# Parse optional arguments.
from optparse import OptionParser
parser = OptionParser()
parser.set_usage(__doc__[1:-1])
parser.add_option('-e', '--encoding', dest='encoding')
parser.add_option('-d', '--dump', action='store_true', dest='dump')
parser.add_option('-l', '--no-latex', action='store_false', dest='latex')
parser.add_option('-o', '--output', action='store', dest='output')
parser.set_defaults(
    encoding='utf-8',
    dump=False,
    latex=True,
    output=None
    )
(options, args) = parser.parse_args()

# ______________________________________________________________________
# Parse required arguments.
if len(args) < 2: 
    sys.stderr.write("Incorrect number of arguments.  Try -h.\n")
    sys.exit(1)
grammarfilenm = args[0]
intexs = args[1:]

# ______________________________________________________________________
# If output file is specified, check whether it is out of date first.
outfile = astutil.open_output_file(options.output, __file__, [grammarfilenm])

# ______________________________________________________________________
# Parse grammar.
grammarfile = codecs.open(grammarfilenm, "r", options.encoding)
gr = grparse(grammarfilenm, grammarfile)
if not gr: sys.exit(1)
if options.dump:
    gr.dump()
gr.postprocess()
if options.dump:
    gr.dump()

# ______________________________________________________________________
# Open .tex file(s).
for intex in intexs:
    texfile = codecs.open(intex, "r", options.encoding)
    u_tex = texfile.read()
    splits_u = re.split("\$\$([^$]*)\$\$", u_tex)
    result = []
    for i in range(len(splits_u)):
        if (i % 2) == 0:
            u_rawtex = splits_u[i]
            result.append(latex(u_rawtex, False, True))
        else:
            u_prod = splits_u[i]                
            u_prod = u_prod.replace("\n", " ")
            if u_prod[0] == "(" and u_prod[-1] == ")":
                u_prod = u_prod[1:-1]
                wrapper = ("\[", "\]")
            else:
                wrapper = ("$", "$")
            prod = parse_prod(u_prod)
            prod.postprocess(gr.nts, gr.terminals, u" ".join(gr.substs))
            if options.dump: prod.dump()
            result.append(wrapper[0])
            result.append(prod.latex_str())
            result.append(wrapper[1])
    outfile.write("".join(result))
    outfile.write("\n")
