#!/usr/bin/env python

"""This program fits a f0 curve with a set of orthogonal
polynomials, then returns the coefficients.
Input is a single column, and zero frequency points are
given zero weight.
"""


import sys
import ortho_fit
from gmisclib import Num


if __name__ == '__main__':
	N = int(sys.argv[1])
	assert N>0, "First argument is the number of Legendre polynomials."
	
	wt = []
	y = []
	for line in sys.stdin.readlines():
		line = line.strip()
		if line.startswith('#'):
			continue
		elif line == '':
			continue
		f = float(line)
		y.append( f )
		if f < 1.0:
			wt.append( 0.0 )
		else:
			wt.append( 1.0 )

	n = len(y)
	x = 2*(Num.arrayrange(n)+0.5)/float(n) - 1
	y = Num.array(y)

	soln, sumwt, svr = ortho_fit.ortho_fit(x, y,
						wt, N,
						name='Legendre')

	print "Solution:"
	print "\tCoefficients:", ' '.join(['%g' % cc for cc in soln.c])
	print "\tError:", soln.e
