"""generate the rml source for rml userguide using 2 preppy passes"""
import sys
# this should be integrated into rml2pdf somehow
SHOW_PAGE_NO = 0

def progress(pageNo):
    print 'rendering page %d' % pageNo
    
def gen(outfile="rml_user_guide_generated.rml", showPageNo=SHOW_PAGE_NO,outDir=None):
    from rlextra.preppy import preppy
    print "compiling preppy (takes a while on some machines the first time after a change)"
    template = preppy.getModule("rml_user_guide")
    print "now running template"
    # run the template twice to get table of contents substitutions
    D = {}
    for run in (1,2):
        f = open(outfile, "w")
        template.run(D, outputfile=f)
        print "run", run, "wrote", outfile #, D
        f.close()
    print "rml generation complete", outfile
    from rlextra.rml2pdf import rml2pdf
    import os
    dtddir = os.path.abspath("..")

    if SHOW_PAGE_NO:
        cb = progress
    else:
        cb = None
    rml2pdf.go(open(outfile).read(), dtdDir=dtddir, pageCallBack=cb,outDir=outDir)
    #print rml2pdf.__file__
    print "pdf generation complete"

def gen2(outfile="rml_user_guide_generated.rml", showPageNo=SHOW_PAGE_NO,outDir=None):
    "for testing the integration of preppy with rml2pdf.go: always regenerates preppy module in memory"
    from rlextra.rml2pdf import rml2pdf
    import os
    dtddir = os.path.abspath("..")
    xmltext = open("rml_user_guide.prep").read()
    if SHOW_PAGE_NO:
        cb = progress
    else:
        cb = None
    rml2pdf.go(xmltext, dtdDir=dtddir, pageCallBack=cb,
               preppyDictionary={"DULL":1}, preppyIterations=2, verbose=SHOW_PAGE_NO,outDir=outDir)

profiling = 0
if __name__=="__main__":
    if '-p' in sys.argv:
        SHOW_PAGE_NO = 1    
    timing = '-t' in sys.argv
    outDir = filter(lambda x: x[:9]=='--outdir=',sys.argv)
    if outDir:
        map(sys.argv.remove,outDir)
        outDir = (outDir[0].split('=')[1]).strip()
    else:
        outDir = None
    if timing:
        from time import time
        t0 = time()
    if profiling:
        import profile
        profile.run("gen(outDir=outDir)")
    else:
        gen2(showPageNo=SHOW_PAGE_NO,outDir=outDir)
    if timing: print 'Took %.2f"' % (time()-t0)
