#! /usr/bin/env python
import sys
import string
import re

from string import split

people = ['DG', 'DM', 'CC', 'PB']

_comment = re.compile( "^\s*(#.*)?$" )
_credit = re.compile( "^\s*\+([A-Za-z,]+)\s+([-+0-9.]+)\s*(?:#.*)?$" )
_debit = re.compile( "^\s*\-([A-Za-z,]+)\s+([-+0-9.]+)\s*(?:#.*)?$" )
_setpeople = re.compile( "^\s*people\s+([A-Za-z,]+)\s*(?:#.*)?$" )
_subtotal = re.compile( "^\s*subtotal\s*(?:#.*)?$" )

def inittables(cr,db):
    for p in people:
	if not cr.has_key(p):
	    credits[p] = 0.0
	if not db.has_key(p):
	    debits[p] = 0.0

credits = {}
debits = {}
inittables(credits,debits)

inputnames = sys.argv[1:]

if inputnames == []:
    inputnames = ['-']

for name in inputnames:
    if  name == '-':
	file = sys.stdin
	print "Reading from <stdin>"
    else:
	file = open(name, "r")
	print "Reading %s..." % name
    #
    for line in file.readlines():
	if _comment.match(line):
	    str = _comment.match(line).group(1)
	    if str:
		print str
	    continue
	cr = _credit.match(line)
	db = _debit.match(line)
	sp = _setpeople.match(line)
	st = _subtotal.match(line)
	if cr:
	    pp = split(cr.group(1), ',')
	    amt = float( cr.group(2) )
	    for p in pp:
		credits[p] = credits[p] + amt/(len(pp))
	elif db:
	    pp = split(db.group(1), ',')
	    amt = float( db.group(2) )
	    for p in pp:
		debits[p] = debits[p] + amt/(len(pp))
	elif sp:
	    pp = split(sp.group(1), ',')
	    people = pp
	    inittables(credits,debits)
	    print "People are: ", people
	elif st:
	    str = "SUBTOTAL:"
	    totcr = 0.0
	    totdb = 0.0
	    for p in people:
		str = ("%s\t%s: %.3f (%.3f)" %
		       (str, p, credits[p], debits[p]))
		totcr = totcr + credits[p]
		totdb = totdb + debits[p]
	    str = str + "\n"
	    sys.stdout.write(str)
	    sys.stdout.write( "\tTotal credits: %.2f\tTotal debits: %.2f\tDiscrepancy: %f\n" % (totcr, totdb, totcr-totdb))
	else:
	    print "Syntax error in %s: %s" % (name, line)
	    sys.exit(2)

sys.stdout.write("\nFinal debts:\n")
debt = {}
total = 0.0
for p in people:
    debt[p] = debits[p] - credits[p]
    total = total + debt[p]
    if debt[p] != 0.0:
	print "\t%s owes %.3f" % (p, debt[p])

print "$%f is unaccounted for." % total
