#!/usr/bin/python

# Extracts all the python code from entec.tex and puts it in the file entec.py

import os, sys

F = open("bsd.tex","r")
P = open("examples.txt","w")
P.write("##################################################\n")
P.write("# ent.py -- Element Number Theory \n")
P.write("# (c) William Stein, 2004\n")
P.write("##################################################\n\n\n\n")

max_len = 69

output = False
section = ""
session = False
sessions = ""
for x in F.readlines():
    if x.find("section") != -1:
        i = x.find("{")
        j = x.find("}")
        section = x[i+1:j]
    if x.find("begin{verbatim}") != -1:
        output = True
        if section != "" and session == False and section!="intersection.":
            P.write("\n##################################################\n")
            P.write("## %s\n"%section)
            P.write("##################################################\n\n")
            section = ""
        continue
    elif x.find("end{verbatim}") != -1:
        output = False
        session = False
        P.write("\n")
        continue
    elif x.find("%session") != -1:
        session = True
    if output:
        if len(x) >= max_len:
            x += "# ****** overfill (len = %s) ******\n"%len(x)
        if session:
            sessions += x
        else:
            P.write(x)

P.write("\n\n##########################################################\n")
P.write("# The following are all the examples not in functions.   #\n")
P.write("##########################################################\n\n")
P.write('def examples():\n    """\n')
for x in sessions.split("\n"):
    P.write("    %s\n"%x)
P.write('    """\n\n')

P.write("""
if __name__ ==  '__main__':
    import doctest, sys
    doctest.testmod(sys.modules[__name__])
""")
