#!/usr/bin/env python
#
# Copyright (C) 2012  Chad Hanna
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import sys
import copy

import pygtk
pygtk.require('2.0')
import pygst
pygst.require('0.10')

from gstlal.svd_bank import read_bank
import numpy
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()

import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot

print >>sys.stdout, 'Expires: Mon, 26 Jul 1997 05:00:00 GMT'
print >>sys.stdout, 'Content-type: text/html\r\n'

print """
<html>
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
</head>
<body bgcolor=#E0E0E0>
"""

# title
print """
<font size=10>SVD BANK</font><br>
"""

bank = path = read_bank(form.getlist("url")[0])

# get the template number
tmps = bank.bank_fragments[0].mix_matrix.shape[1] / 2

for n in range(tmps):
	pyplot.figure(figsize=(18,6))
	pyplot.subplot(211)
	print "<div>"
	maxrate = 0
	mint = 0
	for frag in bank.bank_fragments:
		m = frag.mix_matrix
		s = frag.singular_values
		u = frag.orthogonal_template_bank
		h = numpy.dot(m.T, u)
		t = numpy.linspace(-frag.end, -frag.start, h.shape[1])
		pyplot.plot(t, h[2 * n,:] * frag.rate**.5)
		pyplot.plot(t, h[2 * n + 1,:] * frag.rate**.5)
		maxrate = max(maxrate, frag.rate)
		mint = min(t[0], mint)
	pyplot.xlabel('time (s)')
	#pyplot.xlim([-.5, 0])

	pyplot.subplot(212)
	pyplot.xlabel('samples')
	l = len(bank.autocorrelation_bank[n,:])
	ts = l / float(maxrate)
	t = numpy.linspace(-ts, 0, l)
	pyplot.plot(numpy.real(bank.autocorrelation_bank[n,:]))
	pyplot.plot(numpy.imag(bank.autocorrelation_bank[n,:]))
	pyplot.savefig(sys.stdout, format="svg")
	print "</div>"


print "</body></html>"
