#!/usr/bin/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.


### A program to plot a psd such as one generated by gstlal_reference_psd


from optparse import OptionParser
import os


import lal
from glue.ligolw import utils as ligolw_utils
from gstlal import plotpsd


plotpsd.matplotlib.rcParams.update({
	"font.size": 10.0,
	"axes.titlesize": 10.0,
	"axes.labelsize": 10.0,
	"xtick.labelsize": 8.0,
	"ytick.labelsize": 8.0,
	"legend.fontsize": 8.0,
	"figure.dpi": 300,
	"savefig.dpi": 300,
	"text.usetex": True,
	"path.simplify": True
})


def parse_command_line():
	parser = OptionParser()
	parser.add_option("-o", "--output", help = "Set plot filename (default = replace input file's extension with .png).")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, filenames = parser.parse_args()

	if not filenames:
		raise ValueError("must supply at least one input filename")
	if options.output and len(filenames) > 1:
		raise ValueError("must supply only one input file when setting --output")

	return options, filenames


options, filenames = parse_command_line()


for fname in filenames:
	if options.output:
		outname = options.output
	else:
		outname = os.path.join(os.path.splitext(fname)[0], ".png")

	fig = plotpsd.plot_psds(
		lal.series.read_psd_xmldoc(
			ligolw_utils.load_filename(
				fname,
				verbose = options.verbose,
				contenthandler = lal.series.PSDContentHandler
			)
		),
		plot_width = 2400
	)

	fig.savefig(outname)
