#!/usr/bin/env python
#
# Copyright (C) 2010  Leo Singer
#
# 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.
"""
Prune duplicate mass pairs from a template bank.
lalapps_tmpltbank often places the same template more than once.
"""


__prog__ = "gstlal_prune_duplicate_mass_pairs"

from glue.ligolw import lsctables
from glue.ligolw import utils
from glue.ligolw.utils import process as ligolw_process
import sys

filename, out_filename = sys.argv[1:3]

bank_xmldoc = utils.load_filename(filename, gz=filename.endswith(".gz"))
process = ligolw_process.append_process(bank_xmldoc, __prog__, cvs_repository="gstlal")
ligolw_process.append_process_params(bank_xmldoc, process, ((filename, u"string", ""),(out_filename, u"string", "")))
bank_sngl_table = lsctables.table.get_table( bank_xmldoc,lsctables.SnglInspiralTable.tableName )

mass_pairs = set()
for i, child in enumerate(bank_sngl_table):
	mass_pair = (child.mass1, child.mass2)
	if mass_pair in mass_pairs:
		del bank_sngl_table[i]
	mass_pairs.add(mass_pair)

ligolw_process.set_process_end_time(process)
utils.write_filename(bank_xmldoc, out_filename, gz=out_filename.endswith(".gz"))
