#!/kunden/homepages/9/d92057734/htdocs/.htapps/bin/python
import cgi
import cgitb
cgitb.enable()
import re
from polynomial2 import sanitize,tokenize,shunting_yard,eval_rpn,eval_exp
def step_by_step(expression):
    clean = sanitize(expression)
    yield clean
    tokens = tokenize(clean)
    yield tokens
    rpn = shunting_yard(tokens)
    yield rpn
    yield eval_rpn(rpn)
def superscript(text):
    return re.sub(r'\^([0-9]+|[0-9]\+.[0-9]+)',r'<sup>\1</sup>',text)
def format(_list):
    s = str(_list)
    for char in '"\'[],':
        s = s.replace(char,'')
    return cgi.escape(s)
form = cgi.FieldStorage()
expression = form.getfirst('expression')
expand = form.getfirst('expanded') == 'True'
print "Content-Type: text/html\n"
style = """\
<style>
fieldset {width:"50%"}
fieldset.legend {font-weight:bold}
</style>"""
print "<html><head><title>Polynomial Evaluation</title>%s</head><body>" % style
print "The polynomial evaluator is totally unreliable, and thus should not be used for situations such as math homework<br>"
if expression:
    if 'answertolifetheuniverseandeverything' in expression.replace(' ','').replace(',','').lower():
        expression = '24'
    text = superscript(cgi.escape(str(expression)))
    print '<fieldset><legend>Evaluation of "%s"</legend>' % text
##    try:
    if expand:
        print """Sanitized form:<pre>  <code>%s</code></pre><br>
        Tokenized form:<pre>  <code>%s</code></pre><br>
        <acronym title="Reverse Polish Notation">RPN</acronym>
        form:<pre>  <code>%s</code></pre><br>
        Final evaluation:<pre>  <code>%s</code></pre>""" % tuple([format(step) for step in step_by_step(expression)])
    else:
        print """<pre>  <code>%s</code></pre>"""  % superscript(str(eval_exp(expression)))
##    except:
##        print "<pre>  ERROR while evaluating</pre><br>"
    print '</fieldset>'
print """<fieldset><legend>Polynomial Evaluation</legend>
    Exponentiation is denoted by <kbd>^</kbd> (ie <kbd>a^2</kbd> for a<sup>2</sup>) and
    <kbd>a^2b^2</kbd> = a<sup>2</sup>b<sup>2</sup>,not a<sup>2b<sup>2</sup></sup>.<br>
    <form method="post" action="polynomial_eval.py">
    <input type="text" name="expression" size=35><input type="submit" value="Evaluate">
    <input type="checkbox" name="expanded" value="True"%s>Expanded display
    </form></fieldset></body></html>""" % ((expand and [' checked'] or [''])[0])

