import cgitb
cgitb.enable()

import cgi
import os
import sys

def bool(s):
	try: return int(s)
	except ValueError: pass
	return s == 'on'

def commafy(s):
	s = str(int(s))
	o = ''
	while len(s) > 3:
		o = ',' + s[-3:] + o
		s = s[:-3]
	return s + o

def escape(s):
    return str(s).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')

def form_get(form, name, default, conv=str):
	try:
		item = form[name]
	except KeyError:
		return default
	if item.file:
		print("Uploads are not allowed!")
		sys.exit(1)
	if type(item.value) is not type(''):
		print("Multiple values are not allowed!")
		sys.exit(1)
	try:
		value = conv(item.value)
	except:
		print("'%s' failed to convert" % name)
		sys.exit(1)
	return value

class EvalDict:
	def __init__(self, values):
		self.values = values
	def __getitem__(self, key):
		return escape(eval(key, self.values))

def row(a,b,bold=0):
	pre = post = ''
	if bold:
		pre = '<b>'
		post = '</b>'
	print('<tr><th align=right>%s:</th><td><tt>%s%s%s</tt></td></tr>' % (
		a, pre, b, post ))
def table_start(): print('<hr><div align=center><table border=1>')
def table_end(): print('</table></div>')

def dumpfile(filename, dict=None):
    # Always resolve relative to this file's directory
    here = os.path.dirname(__file__)
    path = os.path.join(here, filename)

    with open(path, encoding="utf-8") as f:
        data = f.read()

    if dict is not None:
        data = data % dict

    sys.stdout.write(data)
