#!/usr/bin/env python3

"""
Typical Usages:

Re-calculating GraceDb gstlal candidates. This assumes you are login to LIGO-Caltech Computing Cluster and
all data (svd banks, psd ...) are availible on the gracedb and the cluster. You also need obtain certificate
via "ligo-proxy-init" before using this option. Use --save to save the svd banks and psd to disk.

Example 1: Calculate SNRs for two detectors.
$ ligo-proxy-init chiwai.chan
$ gstlal_inspiral_calc_snr \
--gid G348519 \
--observatory H \
--observatory L \
--type H1_HOFT_C00 \
--type L1_HOFT_C00 \
--min-instruments 2 \
--time-slide-file tisi.xml\
--track-psd \
--outdir outputs \
--ranking-stat-output rankingstat.xml.gz \
--coinc-output followup_coinc.xml.gz \
--verbose

Example 2: Calculate SNRs for single detector.
$ ligo-proxy-init chiwai.chan
$ gstlal_inspiral_calc_snr \
--gid G347846 \
--observatory L \
--frame-segments-file framesegments.xml \
--frame-segments-name framesegments \
--time-slide-file tisi.xml\
--min-instruments 1 \
--type L1_HOFT_C00 \
--track-psd \
--outdir outputs \
--ranking-stat-output rankingstat.xml.gz \
--coinc-output followup_coinc.xml.gz \
--verbose

Calculate SNR using LLOID method. You should have access to svd banks and reference psd for this option. For
filter particular template in the svd banks, you should know the --bank-number and the --row-number of the template;
Otherwise, if only --bank-number is provided, SNRs for all templates in the sub-bank will be produced. To limit the
output size, use --start and --end to specify the range of SNR in GPS time.

Example: G348519
$ gstlal_inspiral_calc_snr \
--mode 0\
--data-source frames \
--channel-name H1=GDS-CALIB_STRAIN \
--channel-name L1=GDS-CALIB_STRAIN \
--frame-cache frame.cache \
--gps-start-time 1251009527 \
--gps-end-time 1251009527 \
--time-slide-file tisi.xml\
--reference-psd psd.xml.gz \
--track-psd \
--min-instruments 2 \
--svd-bank H1:H1-GSTLAL_SVD_BANK_258-0-0.xml.gz,L1:L1-GSTLAL_SVD_BANK_258-0-0.xml.gz \
--bank-number 0 \
--row-number 203 \
--outdir outputs \
--ranking-stat-output rankingstat.xml.gz \
--coinc-output followup_coinc.xml.gz \
--start 1251010522 \
--end 1251010532 \
--verbose

Calculate SNR using Finite Impulse Response. Typically, you won't use this option unless you simply want to calculate SNR for one particular
template and you don't have access to the corresponding svd bank which contains the template. To use this option, You should have a Bank file,
see svd_bank_snr.write_bank(). To limit the output size, use --start and --end to specify the range of SNR in GPS time.

Example: G348519
$ gstlal_inspiral_calc_snr \
--mode 1\
--data-source "frames" \
--channel-name H1=GDS-CALIB_STRAIN \
--channel-name L1=GDS-CALIB_STRAIN \
--frame-cache frame.cache \
--time-slide-file tisi.xml\
--gps-start-time 1251009527 \
--gps-end-time 1251011527 \
--reference-psd psd.xml.gz \
--track-psd \
--min-instruments 2 \
--bank H1:H1_templates.xml.gz,L1:L1_templates.xml.gz \
--outdir outputs \
--ranking-stat-output rankingstat.xml.gz \
--coinc-output followup_coinc.xml.gz \
--start 1251010522 \
--end 1251010532 \
--verbose
"""
from collections import defaultdict
from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
import math
import os
import sys
import time

from gstlal import datasource
from gstlal import far
from gstlal import inspiral
from gstlal import lloidparts
from gstlal import multirate_datasource
from gstlal import pipeio
from gstlal import pipeparts
from gstlal import reference_psd
from gstlal import simulation
from gstlal import svd_bank
from gstlal import svd_bank_snr
from gstlal.stats.inspiral_lr import LnLRDensity

import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstAudio', '1.0')
from gi.repository import GObject, Gst, GstAudio
GObject.threads_init()
Gst.init(None)

import lal
from lal import LIGOTimeGPS
from lal import UTCToGPS
import lal.series

from ligo import segments
from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from ligo.lw import param as ligolw_param
from ligo.lw import array as ligolw_array
from ligo.lw import lsctables
from ligo.lw import table
from ligo.lw.utils import segments as ligolw_segments

@ligolw_param.use_in
@ligolw_array.use_in
@lsctables.use_in
class ContentHandler(ligolw.LIGOLWContentHandler):
	pass


@lsctables.use_in
class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass


# disable mkchecktimestamps()
# FIXME:  python plugin broken until we switch to Python 3
pipeparts.mkchecktimestamps = lambda pipeline, src, *args: src

def parse_command_line():
	parser = OptionParser(description = "Using gstlal inspiral pipeline to calculate SNR for template(s)")

	datasource.append_options(parser)

	group = OptionGroup(parser, "Whiten / PSD Options", "Adjust noise spectrum estimation parameter")
	group.add_option("--reference-psd", metavar = "filename", help = "Load noise spectrum from LIGO light-weight XML file (optional).")
	group.add_option("--psd-fft-length", metavar = "seconds", default = 32, type = "int", help = "Length of the FFT used to whiten strain data (default = 32 s).")
	group.add_option("--track-psd", action = "store_true", help = "Enable dynamic PSD tracking. Enabled by default if --reference-psd is not given.")
	group.add_option("--zero-pad", metavar = "seconds", default = 0, type = "int", help = "The zero padding of the Hanning window in seconds (default = 0).")
	group.add_option("--average-samples", default = 64, type = "int", help = "The number of samples used to estimate the average value of the PSD")
	group.add_option("--median-samples", default = 7, type = "int", help = "The number of samples used to estimate the median value of the PSD")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Template Options", "Choose a template from a SVD bank file / a bank file (see svd_bank_snr.Bank).")
	group.add_option("--svd-bank", metavar = "filename", help = "A LIGO light-weight xml / xml.gz file containing svd bank information. These can be given as a comma separated list such as H1:file1,H2:file2,L1:file3 to analyze multiple instruments (require)." )
	group.add_option("--coinc", metavar = "filename", help = "The coinc.xml file associated with --svd-bank. This is used to find the --bank-number and --row-number for a particular event. If given, the --bank-number and --row-number will be overwritten. (optional)")
	group.add_option("--bank-number", type = "int", help = "Bank id is of the form <int>ID_<int>N where N is the sub bank id. (optional). SNRs in all banks will be used if it is not given.")
	group.add_option("--bank-counts", type = "int", default = 1, help = "Number of banks to used; Counted from --bank-number; default = 1")
	group.add_option("--row-number", type = "int", help = "The row number of the template (optional). All the SNRs will be outputed if it is not given.")
	group.add_option("--row-counts", type = "int", default = 1, help = "Number of rows to be outputted; Counted from --row-number; default = 1")
	group.add_option("--bank", metavar = "filename", help = "LIGO light-weight xml.gz file(s) containing only one template. These can be given as a comma separated list such as H1:file1,H2:file2,L1:file3. Expecting one template only for each file (require).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Data Quality Options", "Adjust data quality handling")
	group.add_option("--ht-gate-threshold", metavar= "sigma", type = "float", default = float("inf"), help = "Set the threshold on whitened h(t) to excise glitches in units of standard deviation (defalut = inf). ")
	group.add_option("--veto-segments-file", metavar = "filename", help = "Set the name of the LIGO light-weight XML file from which to load vetoes (optional).")
	group.add_option("--veto-segments-name", metavar = "name", default = "vetoes", help = "Set the name of the LIGO light-weight XML file from which to load vetoes (default = 'veto') (optional).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "GraceDb Event Options", "Produce SNR time series for gstlal gracedb event.")
	group.add_option("--gid", metavar = "gracedb event id", type = "str", help = "The gracedb event id.")
	group.add_option("--observatory", metavar = "OBS", type = "str", action = "append", help = "Name of the observatory (H,L,V ...), also see gwdatafind.")
	group.add_option("--type", metavar = "frame type", type = "str", action = "append", help = "Name of the observatory (H,L,V ...), also see gwdatafind.")
	group.add_option("--time-span", metavar = "seconds", type = "int", default = 500, help = "The time span around the event's trigger time, must be larger or equal to 500s (default = 500).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Trigger Generator Control / Outputs Options", "Adjust the trigger generator's behaviors and its outputs.")
	group.add_option("--FAR-trialsfactor", metavar = "trials", type = "float", default = 1.0, help = "Add trials factor to FAR before uploading to gracedb (default = 1.0).")
	group.add_option("--likelihood-snapshot-interval", type = "float", metavar = "seconds", help = "How often to snapshot candidate and ranking statistic data to disk when running online (optional).")
	group.add_option("--ranking-stat-pdf", metavar = "url", help = "Set the URL from which to load the ranking statistic PDF.  This is used to compute false-alarm probabilities and false-alarm rates and is required for online operation (when --data-source is framexmit or lvshm).  It is forbidden for offline operation (all other data sources)")
	group.add_option("--ranking-stat-input", metavar = "url", help = "Set the URL from which to load a ranking statistic definition.  When this is enabled, signal candidates will have ranking statistic values assigned on-the-fly.  Required when --data-source is lvshm or framexmit;  must also set --likelihood-snapshot-interval.")
	group.add_option("--zerolag-rankingstat-pdf", metavar = "url", help = "Record a histogram of the likelihood ratio ranking statistic values assigned to zero-lag candidates in this XML file.  This is used to construct the extinction model and set the overall false-alarm rate normalization during online running.  If it does not exist at start-up, a new file will be initialized, otherwise the counts will be added to the file's contents.  Required when --data-source is lvshm or framexmit;  optional otherwise.")
	group.add_option("--time-slide-file", metavar = "filename", help = "Set the name of the xml file to get time slide offsets (require).")
	group.add_option("--min-instruments", metavar = "count", type = "int", default = 2, help = "Set the minimum number of instruments that must contribute triggers to form a candidate (default = 2).")
	group.add_option("--singles-threshold", metavar = "SNR", type = "float", default = float("inf"), help = "Set the SNR threshold at which to record single-instrument events in the output (default = +inf, i.e. don't retain singles).")
	group.add_option("--control-peak-time", metavar = "seconds", type = "int", help = "Set a time window in seconds to find peaks in the control signal (optional, default is to disable composite detection statistic).")
	group.add_option("--coincidence-threshold", metavar = "seconds", type = "float", default = 0.005, help = "Set the coincidence window in seconds (default = 0.005 s).  The light-travel time between instruments will be added automatically in the coincidence test (default = 0.005).")

	group.add_option("--gracedb-service-url", metavar = "url", type = "str", help = "Fake graceDb service url. This can only be a local url (optional).")
	group.add_option("--gracedb-far-threshold", metavar = "Hertz", type = "float", help = "False-alarm rate threshold for fake gracedb uploads in Hertz (default = do not upload to gracedb).")
	group.add_option("--gracedb-group", metavar = "name", default = "Test", help = "Gracedb group to which to upload events (default = 'Test').")
	group.add_option("--gracedb-pipeline", metavar = "name", default = "gstlal", help = "Name of pipeline to provide in fake GracedB uploads (default = 'gstlal').")
	group.add_option("--gracedb-search", metavar = "name", default = "event-followup", help = "Name of search to provide in fake GracedB uploads (default = 'event-followup').")
	group.add_option("--reconstruction-segment", metavar = "start:stop", action = "append", help = "Only reconstruct the SNRs for this time interval. Note: Use this carefully, this is not compatible with the option --start and --end. This is only added for coincidence document (optional).")
	group.add_option("--ranking-stat-output", metavar = "filename", default = None, help = "Set the name of the file to which to write ranking statistic data collected from triggers. This will not be prefixed by --outdir (optional).")
	group.add_option("--coinc-output", metavar = "filename", help = "Set the name of the LIGO light-weight XML output file *.{xml,xml.gz} or an SQLite database *.sqlite. This will not be prefixed by --outdir (default is disable coinc output) (Providing this would also enable triggers generation, otherwise trigger generator is not added to the pipeline).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Output Control Options", "Control SNR outputs.")
	group.add_option("--outdir", metavar = "directory", default = ".", type = "str", help = "Output directory for SNR(s) (default = .).")
	group.add_option("--complex", action = "store_true", help = "Choose whether to output the complex snr or not.")
	group.add_option("--start", metavar = "seconds", type = "float", help = "Start SNR time series at GPS time '--start' (require).")
	group.add_option("--end", metavar = "seconds", type = "float", help = "End SNR time series at GPS time '--end' (require).")
	parser.add_option_group(group)

	group = OptionGroup(parser, "Program Options", "Control Program Behaviour.")
	group.add_option("--fir-stride", metavar = "seconds", type = "float", default = 8, help = "Set the length of the fir filter stride in seconds. default = 8")
	group.add_option("--verbose", action = "store_true", help = "Be verbsoe.")
	group.add_option("--comment", metavar = "message", help = "Set the string to be recorded in comment and tag columns in various places in the output file (optional).")
	group.add_option("--save", action = "store_true", default = False, help = "Save frame cache / svd bank / psd if using --gid (default = False).")
	group.add_option("--mode", metavar = "method", type = "int", default = 0, help = "The method (0 = LLOID / 1 = FIR) that is used to calculate SNR (default = 0).")
	group.add_option("--output-width", metavar = "bits", type = "int", default = 32, help = "The size of the output data, can only be 32 or 64 bits (default = 32 bits).")
	group.add_option("-t", "--tmp-space", metavar = "path", help = "Path to a directory suitable for use as a work area while manipulating the database file.  The database file will be worked on in this directory, and then moved to the final location when complete.	This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
	parser.add_option_group(group)

	options, args = parser.parse_args()

	#
	# Bait out from here if --gid is provided, else continue setting the program
	#

	if options.gid is not None:
		# Setting up inputs for GraceDb event, this will overwrite svd-bank/template/psd related inputs.
		if options.observatory is None or options.type is None:
			raise ValueError("When using --gid, --observatory and --type must be provided.")
		else:
			gwdata_metavars = svd_bank_snr.framecache_from_event(options.gid, options.observatory, options.type, time_span = options.time_span, outdir = options.outdir, verbose = options.verbose)
			# We can hardcoded here, since we know all the information from gracedb.
			# This assume everything on the gracedb are correct and complete which could go wrong in the future.
			# (e.g files are deleted)
			options.data_source = "frames"
			options.frame_cache = os.path.join(options.outdir, "frame.cache")
			options.gps_start_time = gwdata_metavars["gps_start_time"][0]
			options.gps_end_time = gwdata_metavars["gps_end_time"][0]
			options.channel_name = gwdata_metavars["channels_name"]
			options.instrument = gwdata_metavars["instruments"]
			gw_data_source_info = datasource.GWDataSourceInfo(options)

			# FIXME: Adjustable parameters, hardcoded here for simplicity.
			trigger_time = min(gwdata_metavars["trigger_times"])
			options.start = trigger_time - 5
			options.end = trigger_time + 5

			# It must be using LLOID
			options.mode = 0

			psds_dict = svd_bank_snr.psd_from_event(options.gid, save = options.save, verbose = options.verbose)

			banks_dict, options.bank_number, options.row_number = svd_bank_snr.svd_banks_from_event(options.gid, save = options.save, verbose = options.verbose)

			# bait out from here
			return options, gw_data_source_info, banks_dict, psds_dict

	#
	# Do general program options checking
	#

	if options.outdir is None:
		missing_required_options.append("--outdir")

	# Check SNRs series output
	if options.start is None or options.end is None:
		raise ValueError("Must have --start and --end.")
	elif options.start >= options.end:
		raise ValueError("--start must less than --end.")

	#
	# Setting up GW data
	#

	# Extra handle for SNRs output because SNRs are not stable initially and have padding at the end
	# FIXME: the 50s is hardcoded and only use to avoid snr being unstable due to edge effect when doing convoluion
	gw_data_source_info = datasource.GWDataSourceInfo(options)
	if options.start - gw_data_source_info.seg[0] <= 50 or gw_data_source_info.seg[1] - options.end <= 50:
		raise ValueError("Check your inputted --start / --end or your frame file. You should have a long enough data such that, the --start/--end is larger/less than the start/end of your data at least 50s. ")

	#
	# Setting up PSD
	#

	if options.reference_psd:
		psd = lal.series.read_psd_xmldoc(ligolw_utils.load_url(options.reference_psd, contenthandler = lal.series.PSDContentHandler))
		# Check if there enough reference psds for GW data
		if set(psd) < set(gw_data_source_info.channel_dict):
			raise ValueError("Missing PSD(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(psd)))))
	else:
		psd = dict((ifo, None) for ifo in set(gw_data_source_info.channel_dict))
		options.track_psd = True

	#
	# Setting up SVD banks (mode 0 = LLOID) or template table (mode 1 = FIR)
	#

	assert options.bank_counts >= 1, "Number of banks to be used and outputted must be larger than or equals to 1." 
	assert options.row_counts >= 1, "Number of rows to be outputted must be larger than or equals to 1." 
	# Use LLOID method
	if options.mode == 0:
		missing_required_options = []
		# Checking required options
		if options.svd_bank is None:
			missing_required_options.append("--svd-bank")
		# Raise VauleError is required option(s) is/are missing
		if missing_required_options:
			raise ValueError("Missing required option(s) %s" % ", ".join(sorted(missing_required_options)))

		# Setting up SVD bank
		bank_urls = inspiral.parse_svdbank_string(options.svd_bank)

		# Check if there are enough svd banks for GW data
		if set(bank_urls) < set(gw_data_source_info.channel_dict):
			raise ValueError("Missing SVD bank(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(bank_urls)))))

		banks_dict = inspiral.parse_bank_files(bank_urls, options.verbose)

		# Scan for the --bank-number and --row-number if --coinc is given
		if options.coinc is not None:
			coinc_xmldoc = ligolw_utils.load_url(options.coinc, verbose = options.verbose, contenthandler = ContentHandler)
			options.bank_number, options.row_number = svd_bank_snr.scan_svd_banks_for_row(coinc_xmldoc, banks_dict)

	# Use Finite Impulse Response
	elif options.mode == 1:
		missing_required_options = []
		# Checking required options
		if options.bank is None:
			missing_required_options.append("--bank")
		# Raise VauleError is required option(s) is/are missing
		if missing_required_options:
			raise ValueError("Missing required option(s) %s" % ", ".join(sorted(missing_required_options)))

		bank_urls = inspiral.parse_svdbank_string(options.bank)
		banks_dict = svd_bank_snr.parse_bank_files(bank_urls)

		# Check if there enough templates for GW data
		if set(banks_dict) < set(gw_data_source_info.channel_dict):
			raise ValueError("Missing table(s) for %s." % (", ".join(sorted(set(gw_data_source_info.channel_dict) - set(banks_dict)))))

	# Unknown mode
	else:
		raise ValueError("Invalid mode: %d" % options.mode)

	#
	# Check if --bank-number and --row-number is valid
	#
	for banks in banks_dict.values():
		if options.bank_number is not None and options.row_number is not None:
			if not (0 <= options.bank_number < len(banks)) :
				raise ValueError("Invaild --bank-number %d. Possible id [0-%d)\n" % (options.bank_number, len(banks)))
			if not (0 <= options.row_number < len(banks[options.bank_number].sngl_inspiral_table)):
				raise ValueError("No such template: Invaild --row-number %d. Possible range [0-%d)\n" % (options.row_number, len(banks[options.bank_number].sngl_inspiral_table)))
		elif options.bank_number is None and options.row_number is not None:
			# Just pick one bank
			if not (0 <= options.row_number < len(banks[0].sngl_inspiral_table)):
				raise ValueError("No such template: Invaild --row-number %d. Possible range [0-%d)\n" % (options.row_number, len(banks[0].sngl_inspiral_table)))
		elif options.bank_number is not None and options.row_number is None:
			if not (0 <= options.bank_number < len(banks)) :
				raise ValueError("Invaild --bank-number %d. Possible id [0-%d)\n" % (options.bank_number, len(banks)))
		else:
			# Just to be clear
			pass

	return options, gw_data_source_info, banks_dict, psd

options, gw_data_source_info, banks_dict, psds_dict = parse_command_line()

#====================================================================================================
#
#						Post Setup
#
#====================================================================================================

# Prepare veto segements
if options.veto_segments_file is not None:
	veto_segments = ligolw_segments.segmenttable_get_by_name(ligolw_utils.load_filename(options.veto_segments_file, verbose = options.verbose, contenthandler = LIGOLWContentHandler), options.veto_segments_name).coalesce()
else:
	veto_segments = None

# Choose to optionally reconstruct segments around chosen segement.
# Reconstruct segment around injections is disable.
# if options.injections:
#	offset_padding = max(math.ceil(abs(row.end))+1 for bank in banks_dict.values()[0] for row in bank.sngl_inspiral_table)
#	reconstruction_segment_list = simulation.sim_inspiral_to_segment_list(options.injections, pad = offset_padding)
if options.reconstruction_segment:
	reconstruction_segment_list = segments.segmentlist()
	for reconstruction_segment in options.reconstruction_segment:
		t0, t1 = reconstruction_segment.split(":")
		reconstruction_segment_list.append(segments.segment(LIGOTimeGPS(int(t0)), LIGOTimeGPS(int(t1))))
else:
	reconstruction_segment_list = None
#====================================================================================================
#
#						main
#
#====================================================================================================

if options.verbose:
	sys.stderr.write("Building pipeline...\n")

pipeline = Gst.Pipeline(name = "gstlal_inspiral_SNR")
mainloop = GObject.MainLoop()

#
# Construct Default Pipeline Handler
#


bank_slicing = slice(None, None, None) if options.bank_number is None else slice(options.bank_number, options.bank_number+options.bank_counts, 1)
bank_start = options.bank_number if options.bank_number is not None else 0
bank_snrs_dict = defaultdict(list)
for instrument in gw_data_source_info.channel_dict:
	for num, bank in enumerate(banks_dict[instrument][bank_slicing], bank_start):
		bank_snrs_dict[instrument].append(svd_bank_snr.Bank_SNR(options.start, options.end, instrument, bank, bank_number = num, method = "FIR" if options.mode else "LLOID"))

snr_document = svd_bank_snr.SignalNoiseRatioDocument(bank_snrs_dict, verbose = options.verbose)

if options.coinc_output == None:
	handler = svd_bank_snr.SimpleSNRHandler(pipeline, mainloop, snr_document, verbose = options.verbose)
else:
	handler = svd_bank_snr.Handler(snr_document, verbose = options.verbose)
snr_appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_snr_buffer)

#
# Construct Pipeline 
#

itacac_dict = {}
for instrument in gw_data_source_info.channel_dict:
	src, statevector, dqvector = datasource.mkbasicsrc(pipeline, gw_data_source_info, instrument, options.verbose)
	hoft = multirate_datasource.mkwhitened_multirate_src(
		pipeline,
		src,
		set(rate for bank_SNRs in bank_snrs_dict[instrument] for rate in bank_SNRs.bank.get_rates()),
		instrument,
		dqvector = dqvector,
		fir_whiten_reference_psd = bank.processed_psd,
		ht_gate_threshold = options.ht_gate_threshold,
		psd = psds_dict[instrument],
		psd_fft_length = options.psd_fft_length,
		statevector = statevector,
		track_psd = options.track_psd,
		veto_segments = veto_segments,
		width = options.output_width
	)

	for index, bank_SNR in enumerate(bank_snrs_dict[instrument]):
		bank = bank_SNR.bank
		if options.mode == 0:
			snr = lloidparts.mkLLOIDhoftToSnrSlices(
				pipeline,
				hoft,
				bank,
				(None, None),
				1 * Gst.SECOND,
				control_peak_time = options.control_peak_time,
				fir_stride = options.fir_stride,
				logname = instrument,
				nxydump_segment = None,
				reconstruction_segment_list = reconstruction_segment_list,
				snrslices = None,
				verbose = options.verbose
			)
		else:
			fir_matrix = []
			for template in bank.templates:
				fir_matrix += [template.real, template.imag]
			snr = pipeparts.mktogglecomplex(
				pipeline,
				pipeparts.mkfirbank(
					pipeline,
					hoft[bank.sample_rate],
					latency = 0,
					fir_matrix = fir_matrix,
					block_stride = 16 * bank.sample_rate,
					time_domain = False
					)
				)
		# Construct SNR handler by default and terminate the pipeline at here
		if options.coinc_output == None:
			snr_appsync.add_sink(pipeline, snr, name = "%s_%d" % (instrument, index))
		# Construct optional trigger generator
		else:
			snr = pipeparts.mktee(pipeline, snr)
			snr_appsync.add_sink(pipeline, pipeparts.mkqueue(pipeline, snr), name = "%s_%d" % (instrument, index))

			nsamps_window = 1 * max(bank.get_rates())
			if bank.bank_id not in itacac_dict:
				itacac_dict[bank.bank_id] = pipeparts.mkgeneric(pipeline, None, "lal_itacac")
			head = itacac_dict[bank.bank_id]
			pad = head.get_request_pad("sink%d" % len(head.sinkpads))
			for prop, val in [("n", nsamps_window), ("snr-thresh", LnLRDensity.snr_min), ("bank_filename", bank.template_bank_filename), ("sigmasq", bank.sigmasq), ("autocorrelation_matrix", pipeio.repack_complex_array_to_real(bank.autocorrelation_bank)), ("autocorrelation_mask", bank.autocorrelation_mask)]:
				pad.set_property(prop, val)
			pipeparts.mkqueue(pipeline, snr).srcpads[0].link(pad)

#
# Construct optional LLOID handler instead if --coinc-output is provided
#

if options.coinc_output != None:
	# Prepare offsetvectors
	offsetvectors = lsctables.TimeSlideTable.get_table(ligolw_utils.load_filename(options.time_slide_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose)).as_dict().values()
	all_instruments = reduce(lambda a, b: a | set(b), offsetvectors, set())
	if len(all_instruments) < options.min_instruments:
		raise ValueError("--time-slide-file \"%s\" names %s but we need at least %d instruments" % (options.time_slide_file, ", ".join(sorted(all_instruments)), options.min_instruments))
	if not (all_instruments >= set(gw_data_source_info.channel_dict)):
		raise ValueError("--time-slide-file names %s but have channel names for %s" % (", ".join(sorted(all_instruments)), ", ".join(sorted(gw_data_source_info.channel_dict))))

	# Load template ids and horizon_factors
	sngl_inspiral_table = banks_dict.values()[0][options.bank_number or 0].sngl_inspiral_table.copy()
	horizon_factors = {}
	for bank in banks_dict.values()[0]:
		sngl_inspiral_table.extend(bank.sngl_inspiral_table)
		horizon_factors.update(bank.horizon_factors)
	template_ids = frozenset(row.template_id for row in sngl_inspiral_table)

	if options.ranking_stat_input:
		xmldoc = ligolw_utils.load_url(options.ranking_stat_input, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler)
		rankingstat, _ = far.parse_likelihood_control_doc(xmldoc)
		if rankingstat is None:
			raise ValueError("--ranking-stat-input does not contain parameter distribution data.")
		if rankingstat.template_ids is None:
			rankingstat.template_ids = template_ids
		elif rankingstat.template_ids != template_ids:
			raise ValueError("--ranking-stat-input has wrong template ids.")
		if rankingstat.instruments != all_instruments:
			raise ValueError("--ranking-stat-input does not have the same instruments as defined in --time-slide-file.")
		if rankingstat.delta_t != options.coincidence_threshold:
			raise ValueError("--ranking-stat-input does not have the same delta_t as --coincidence-threshold.")
		if rankingstat.min_instruments != options.min_instruments:
			raise ValueError("--ranking-stat-input does not have the same min_instruments as --min-instruments.")
		rankingstat.numerator.set_horizon_factors(horizon_factors)
	else:
		rankingstat = far.RankingStat(
			template_ids = template_ids,
			instruments = set(gw_data_source_info.channel_dict),
			delta_t = options.coincidence_threshold,
			min_instruments = options.min_instruments,
			horizon_factors = horizon_factors
		)

	coincs_document = inspiral.CoincsDocument(
		url = options.coinc_output,
		process_params = options.__dict__.copy(),
		process_start_time = UTCToGPS(time.gmtime()),
		comment = options.comment,
		instruments = rankingstat.instruments,
		seg = gw_data_source_info.seg,
		offsetvectors = offsetvectors,
		injection_filename = options.injections,
		tmp_path = options.tmp_space,
		replace_file = True,
		verbose = options.verbose
	)

	handler.init(
		mainloop,
		pipeline,
		coincs_document,
		rankingstat,
		banks_dict.values()[0][options.bank_number].horizon_distance_func,
		gracedbwrapper = inspiral.GracedBWrapper(
			rankingstat.instruments,
			far_threshold = options.gracedb_far_threshold,
			min_instruments = options.min_instruments,
			group = options.gracedb_group,
			search = options.gracedb_search,
			pipeline = options.gracedb_pipeline,
			service_url = options.gracedb_service_url,
			upload_auxiliary_data = True,
			verbose = options.verbose
		),
		zerolag_rankingstatpdf_url = options.zerolag_rankingstat_pdf,
		rankingstatpdf_url = options.ranking_stat_pdf,
		ranking_stat_output_url = options.ranking_stat_output,
		ranking_stat_input_url = options.ranking_stat_input,
		likelihood_snapshot_interval = options.likelihood_snapshot_interval,
		sngls_snr_threshold = options.singles_threshold,
		FAR_trialsfactor = options.FAR_trialsfactor,
		verbose = options.verbose
	)

	assert len(itacac_dict.keys()) >= 1
	trigger_appsync = pipeparts.AppSync(appsink_new_buffer = handler.appsink_new_buffer)
	trigger_appsinks = set(trigger_appsync.add_sink(pipeline, src, caps = Gst.Caps.from_string("application/x-lal-snglinspiral"), name = "bank_%s_sink" % bank_id) for bank_id, src in itacac_dict.items())

#
# Run pipeline
#

if options.verbose:
	sys.stderr.write("Setting pipeline state to READY...\n")
if pipeline.set_state(Gst.State.READY) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline cannot enter ready state.")

datasource.pipeline_seek_for_gps(pipeline, *gw_data_source_info.seg)

if options.verbose:
	sys.stderr.write("Seting pipeline state to PLAYING...\n")
if pipeline.set_state(Gst.State.PLAYING) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline cannot enter playing state.")
if options.verbose:
	sys.stderr.write("Calculating SNR...\n")

mainloop.run()

if options.verbose:
	sys.stderr.write("Calculation done.\n")
if pipeline.set_state(Gst.State.NULL) != Gst.StateChangeReturn.SUCCESS:
	raise RuntimeError("pipeline could not be set to NULL.")

# Write outputs
if options.coinc_output != None:
	handler.write_output_url(url = options.coinc_output)
handler.write_snrs(options.outdir, row_number = options.row_number, counts = options.row_counts, COMPLEX = options.complex)

