#!/usr/bin/env python

import math
import ortho_poly
import die
import sys
import g2_select
import os
sys.path.insert(0, '%s/lib' % os.environ['OXIROOT'])
import read_fft_fiat


"""Do a batch reconstruction of orthogonal polynomial fits,
based on input which is contains coefficients
fft.fiat format.
"""


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

N = 100
YRANGE = None
XRANGE = None

def yscale(y):
	return 12.0*math.log(1+y)/math.log(2.0)

if __name__ == '__main__':
	arglist = sys.argv[1:]
	s = None
	pr = 'print'
	id = '"%s/%s" % (d, phid)'
	while arglist and arglist[0].startswith('-'):
		arg = arglist.pop(0)
		if arg == '-n':
			N = int(arglist.pop(0))
		elif arg == '-select':
			s = arglist.pop(0)
		elif arg == '-plot':
			pr = 'plot'
		elif arg == '-order':
			pr = 'order'
		elif arg == '-id':
			id = arglist.pop(0)
		elif arg == '-yr':
			a = float(arglist.pop(0))
			b = float(arglist.pop(0))
			YRANGE = (a, b)
		elif arg == '-xr':
			a = float(arglist.pop(0))
			b = float(arglist.pop(0))
			XRANGE = (a, b)
		elif arg == '--':
			break
		else:
			die.die('Bad arg: %s' % arg)

	filename = arglist[0]
	h, data, c = read_fft_fiat.read(open(filename, 'r'))
	if s is not None:
		data = g2_select.filterlist(s, data)
	OPNAME = h['ORTHONAME']
	op = ortho_poly.F(OPNAME, n=N)
	if pr == 'print':
		for datum in data:
			ae = ['%.3f' % x for x in op.expand(datum['A']) ]
			print g2_select.evaluate(id, datum), ' '.join(ae)
	elif pr == 'order':
		for datum in data:
			print g2_select.evaluate(id, datum), datum['A'].shape[0]
	else:
		import graphite
		import os
		g = graphite.Graph()
		g.formats[0].lineStyle.width = 0.1
		g.axes[graphite.X].tickMarks[0].labels = graphite.AUTO
		g.axes[graphite.Y].tickMarks[0].labels = graphite.AUTO
		g.axes[graphite.X].label.text = 'time, normalized'
		g.axes[graphite.Y].label.text = 'f0 (semitones)'
		g.title.text = '%s/%s' % (os.environ.get('PWD', '?'), str(s))
		if YRANGE:
			g.axes[graphite.Y].range = YRANGE
		if XRANGE:
			g.axes[graphite.X].range = XRANGE
		for datum in data:
			ds = []
			for (i, y) in enumerate( op.expand(datum['A']) ):
				ds.append( (i,yscale(y)) )
			g.datasets.append(graphite.Dataset(ds))
		graphite.genOutput(g, 'PS', canvasname='plot.ps')
