#! /usr/bin/env python

import sys
from icecube.icetray import OMKey
from icecube import dataio, jebclasses, dataclasses
from getopt import getopt

DEEPCORE = ""
veto_top = 20
veto_max = 4
n_events = 1000000000L
output_filename = "dcv.i3.gz"
logfile  = sys.stdout

opts, args = getopt(sys.argv[1:], 'L:M:N:O:V:', [ 'log=', 'filelist=' ])
for o, a in opts:
	if o == '-L' or o == '--log':
		logfile = open(a, "wt")
	elif o == '--filelist':
		args += [ x.strip() for x in open(a) ]
	elif o == '-M':
		veto_max = int(a)
	elif o == '-N':
		n_events = long(a)
	elif o == '-O':
		output_filename = a
	elif o == '-V':
		veto_top = int(a)

i3z = dataio.I3File(output_filename, "w")

class VetoRegion (object):
	def __init__(self):
		self.veto = set()
		for s in range(1, 78):
			for m in range(1, veto_top):
				self.veto.add(OMKey(s, m))

		for s in (16, 17, 18, 19, 24, 25, 26, 27, 28, 33, 34, 35, 36, 37, 38, \
					  43, 44, 45, 46, 47, 48, 53, 54, 55, 56, 57, 62, 63):
			for m in range(1, 61):
				self.veto.add(OMKey(s, m))

		for s in (79, 80, 81, 82, 83, 84, 85):
			for m in range(1, 11):
				self.veto.add(OMKey(s, m))

	def sub(self, test_set):
		return test_set - self.veto

schild = VetoRegion()

evts = 0

try:

	for filename in args:
		i3f = dataio.I3File(filename)
		while i3f.more():
			frame = i3f.pop_physics()
			fmask = frame['FilterMask']
			header = frame['I3EventHeader']
			if len(DEEPCORE) == 0:
				# Auto-guess the filter name
				guess = [ x for x in fmask.keys() if x[0:8] == "DeepCore" ]
				if len(guess) == 0: raise NameError("No suitable DeepCore filter found.")
				if len(guess) != 1: print >>sys.stderr, "WARNING: multiple DeepCore filters found"
				DEEPCORE = guess[0]
			filt  = fmask[DEEPCORE]
			if filt.condition_passed and filt.prescale_passed:
				chan = set(frame['NFEMergedPulses'].keys())
				vcha = schild.sub(chan)
				n    = len(chan)
				m    = len(vcha)
				if n - m <= veto_max: 
					print >>logfile, "%6.6d:%9.9d %s %4.4d %4.4d" % \
						(header.run_id, header.event_id, header.start_time, n, n-m)
					i3z.push(frame)
			evts += 1
			if evts == n_events: raise StopIteration()

except StopIteration:
	pass

finally:
	i3z.close()

