#!/usr/bin/env python
#
# Copyright (C) 2010--2011  Kipp Cannon, 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.


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


from optparse import OptionParser
try:
	import sqlite3
except ImportError:
	# pre 2.5.x
	from pysqlite2 import dbapi2 as sqlite3
import sys


from glue.lal import CacheEntry
from glue import segments
from glue.ligolw.utils import segments as ligolwsegments
from pylal.datatypes import LIGOTimeGPS as GPS
from pylal import ligolw_burca2
from pylal import ligolw_thinca
from gstlal import far
from gstlal import inspiral
from glue.ligolw import utils


__author__ = "Chad Hanna <chad.hanna@ligo.org>"
__version__ = "git id %s" % ""	# FIXME
__date__ = ""	# FIXME


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


def parse_command_line():
	parser = OptionParser(
		version = "Name: %%prog\n%s" % "" # FIXME
	)
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	parser.add_option("-s", "--synthesize-injection-count", metavar = "N", default = 10000000, type = "int", help = "Synthesize an injection distribution with N injections. default 1000000")
	parser.add_option("--write-likelihood", metavar = "filename", help = "Write merged raw likelihood data to this file.")
	parser.add_option("--instrument", action = "append", help = "append to a list of instruments to create dist stats for.  Must be whatever instruments you intend to analyze")
	parser.add_option("--trials-far-thresh", type = "float", help = "set the far threshold for the thresh parameter in the trials table")
	parser.add_option("-p", "--background-prior", metavar = "N", default = 1, type = "float", help = "include an exponential background prior with the maximum bin count = N, default 1")
	options, filenames = parser.parse_args()

	return options, filenames



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


#
# command line
#


options, filenames = parse_command_line()


#
# Create likelihood data
#

coincparamsdistributions = far.DistributionsStats()

if options.background_prior != 0:
	coincparamsdistributions.add_background_prior(options.background_prior, instruments = options.instrument, verbose = options.verbose)

coincparamsdistributions.add_foreground_prior(verbose = options.verbose, n = options.synthesize_injection_count, instruments = options.instrument)

# no segments, this file is independent of time
FAR = far.LocalRankingData(segments.segment(None, None), coincparamsdistributions)

# initialize the trials table to 0
FAR.trials_table.initialize_from_sngl_ifos(options.instrument, count = 0, count_below_thresh = 0, thresh = options.trials_far_thresh)

xmldoc = inspiral.gen_likelihood_control_doc(FAR, options.instrument)
utils.write_filename(xmldoc, options.write_likelihood, gz = options.write_likelihood.endswith('.gz'), verbose = options.verbose)
