#!/usr/bin/env python

import ortho_poly
import sys
import die
import avio


"""Do a batch reconstruction of orthogonal polynomial fits,
based on input which is contains coefficients
in avio format, with names specified by PATTERN.
"""


try:
	enumerate([])
except NameError:
	from g_enumerate import enumerate

PATTERN = 'i%02d'
N = 100


if __name__ == '__main__':
	xa = None
	arglist = sys.argv[1:]
	excel = 0
	OPNAME = Legendre
	while arglist and arglist[0].startswith('-'):
		arg = arglist.pop(0)
		if arg == '-name':
			OPNAME = arglist.pop(0)
		elif arg == '-n':
			N = int(arglist.pop(0))
		elif arg == '-excel':
			excel = 1
		elif arg == '--':
			break
		else:
			die.die('Bad arg: %s' % arg)

	out = []
	for x in sys.stdin:
		if x.startswith('#'):
			continue
		x = x.strip()
		if x == '':
			continue
		a = avio.parse(x)
		i = 0
		c = []
		while PATTERN%i in a:
			c.append( float(a[PATTERN%i]) )
			i += 1
		op = ortho_poly.F(OPNAME, n=N)
		out.append( op.expand(c) )
	for j in range(N):
		tmp = []
		if not excel:
			tmp.append('%d' % j)
			tmp.append('%g' % op.x[j])
		for k in range(len(out)):
			if excel:
				tmp.append('%d' % j)
			tmp.append( '%g' % out[k][j])
		print '\t'.join(tmp)
