#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2023 Leo Tsukada
#
# 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.


### This program converts the old format of diststat files to the new one with
### the ifo-dependent SNR-chisq histogram objects in the signal model
# FIXME : add other new features when those conversion is neccesary in the future


from optparse import OptionParser

from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from gstlal import far
from lal.utils import CacheEntry


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

def parse_command_line():
	parser = OptionParser()
	parser.add_option("--output-file", metavar = "filename", action = "append", help = "Set the name of the output data file to write in disk after conversion. Can be given more than once. If not given, it will overwrite the input file by default. NOTE : File names should file T050017 naming convention, with an integer corresponding to split bank it is associated with (e.g. H1L1-0_DIST_STATS-1127307417-3805.xml.gz)")
	parser.add_option("--output-cache", metavar = "filename", help = "Set the name of the cache file that get added as output files.")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")

	options, filenames = parser.parse_args()
	process_params = dict(options.__dict__)

	options.output_files= []
	if options.output_file:
		options.output_files += options.output_file
	if options.output_cache:
		options.output_files += [CacheEntry(line).url for line in open(options.output_cache)]
	if not options.output_files:
		options.output_files = filenames

	return options, filenames, process_params

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

options, filenames, process_params = parse_command_line()


for output_file, input_file in zip(options.output_files, filenames):
	converted_rankingstat, _ = far.parse_likelihood_control_doc(ligolw_utils.load_filename(input_file, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose), convert=True)
	if converted_rankingstat is None:
		raise ValueError("The given file '%s' does not contain likelihood ratio data" % output_file)
	else:
		xmldoc = ligolw.Document()
		xmldoc.appendChild(ligolw.LIGO_LW())
		process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_diststats_converter", instruments = converted_rankingstat.numerator.instruments, paramdict = process_params)
		far.gen_likelihood_control_doc(xmldoc, converted_rankingstat, None)
		process.set_end_time_now()
		ligolw_utils.write_filename(xmldoc, output_file, verbose = options.verbose)
