#!/usr/bin/env python3
# The Universe 2 Online Calculator v1.00 
# is licensed under the SubText License v1.0.
import cgi, re, os
eqr = cgi.FieldStorage().getvalue('eqr')
eqr = str(eqr)
eqr = eqr.replace('x', '*')
eqr = eqr.replace('X', '*')
eqr = eqr.replace('(', '')
eqr = eqr.replace(')', '')
eqr = eqr.replace('$', '')
eqr = re.sub(r'[a-zA-Z]', '', eqr)
ocver = '1.00'

print('Content-Type: text/html;charset=utf-8')
print('') 
print('<body bgcolor="#c3ffff"><title>Online Calculator</title><center>')
print('<small>Welcome to the <a href="http://universe2.us/">Universe 2</a> online calculator v' + ocver + '.<p></p>')
print('Enter an equation in the box below and press "Calculate".<p></p>')
print('<form action="' + os.environ['SCRIPT_NAME'] + '" method="post">')
print('<input type="text" name="eqr" style="text-align: center" /><p></p>')
print('<input type="submit" value="Calculate" /></form><p></p>______________<p></p>')

if not eqr == '':
 if len(eqr) > 12:
  print('You may not attempt calculations larger than twelve characters.')
 elif '**' in eqr:
  print('This operation could cause a very large calculation delay and slow down the whole server,<br>therefore it has been disabled.')
 else:
  try:
   calcresult = str(eval(eqr)).replace('True', '<b><font color="#00cc00">True</font></b>').replace('False', '<b><font color="#cc0000">False</font></b>')
   print('Your result is:<br><div style="width: 214px; border: 3px solid blue"><p style="margin: 0; padding: 7px">' + calcresult + '</div></p>')
  except:
   print('Unable to calculate.<br>Invalid or unrecognized equation:<br><div style="width: 214px; border: 3px solid red"><p style="margin: 0; padding: 7px">')
   print(str(eqr) + '</div></p>')
else:
 print('No equation.')
print('</center><font size="1"><div align="right"><a href="http://universe2.us/u2calc.tar.gz">Download for your site</a></div></font></small>')
