#!/usr/bin/env python
#
# Copyright (C) 2013  Kipp Cannon, Chad Hanna, Drew Keppel
#
# 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.

## @file
# A program to read data, possibly downsample and add injections and cache it to local disks.
#
# ### Command line interface
#	+ `--output-path` [path]: Set the path where the output frame files are to be written (default = value of TMPDIR environment variable if set, otherwise the current working directory).
#	+ `--sample-rate` [Hz] (int): Downsample to this sample rate (default = no resampling).
#	+ `--verbose`: Be verbose (optional).

#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


import os
import sys
from optparse import OptionParser


# The following snippet is taken from http://gstreamer.freedesktop.org/wiki/FAQ#Mypygstprogramismysteriouslycoredumping.2Chowtofixthis.3F
import pygtk
pygtk.require("2.0")
import gobject
gobject.threads_init()
import pygst
pygst.require("0.10")
import gst


from gstlal import datasource
from gstlal import pipeparts
from gstlal import hoftcache

pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src

def excepthook(*args):
	# system exception hook that forces hard exit.  without this,
	# exceptions that occur inside python code invoked as a call-back
	# from the gstreamer pipeline just stop the pipeline, they don't
	# cause gstreamer to exit.

	# FIXME:  they probably *would* cause if we could figure out why
	# element errors and the like simply stop the pipeline instead of
	# crashing it, as well.  Perhaps this should be removed when/if the
	# "element error's don't crash program" problem is fixed
	sys.__excepthook__(*args)
	os._exit(1)

sys.excepthook = excepthook


#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


def parse_command_line():
	parser = OptionParser(
		description = __doc__
	)
	parser.add_option("--output-path", metavar = "path", default = os.environ.get("TMPDIR", "."), help = "Set the path where the output frame files are to be written (default = value of TMPDIR environment variable if set, otherwise the current working directory).")
	parser.add_option("--sample-rate", metavar = "Hz", type = "int", help = "Downsample to this sample rate (default = no resampling).")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")
	datasource.append_options(parser)

	options, filenames = parser.parse_args()

	options.description = "CBC_TMP"

	try:
		output_cache_filename, = filenames
	except ValueError:
		raise ValueError("must provide exactly one output cache filename")

	return options, output_cache_filename


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


#
# parse command line
#


options, output_cache_filename = parse_command_line()
data_source_info = datasource.GWDataSourceInfo(options)


#
# Cache h(t)
#


cache = hoftcache.cache_hoft(data_source_info, output_path = options.output_path, sample_rate = options.sample_rate, description = options.description, verbose = options.verbose)


#
# Write cache
#


if options.verbose:
	print >>sys.stderr, "writing %s ..." % output_cache_filename
cache_file = open(output_cache_filename, "w")
for entry in cache:
	print >>cache_file, str(entry)


#
# done
#
