#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, os.path, sys, argparse, codecs


def resize_window(tuples_file, output, left, right, remove=False):
	print "Loading file.."
	counter = 1
	with codecs.open(tuples_file, "r", 'utf-8') as file:
		no_lines = sum(1 for line in file)
		file.seek(0)
		with codecs.open(output, 'w','utf=8') as out:
			for line in file:
				if (counter % 1000000) == 0:
					print "Processed %d/%d"%(counter, no_lines)
				counter +=1
				parts = line.split(';')
				flex_pos = parts[1].rfind(':')
				if remove:
					parts[1] = parts[1][:flex_pos]
					out.write(';'.join(parts))
				else:
					r_check=False;
					l_check=False;
					size = int(parts[1][flex_pos+1:len(parts[1])])
					if left!=None:
						l_check = size>=left
					else:
						l_check = True
					if right!=None:
						r_check = size<=right
					else:
						r_check = True

					if l_check and r_check:
						out.write(';'.join(parts))

	print "Done"

def is_int(string):
	try:
		int(string)
	except ValueError:
		return False
	return True

def main():
	parser = argparse.ArgumentParser(description='Window Tuples util')
	parser.add_argument('-t', action='store', dest='tuple', help='Path to tuples file')
	parser.add_argument('-d', action='store_true', dest='remove_size', default=False, help='Removing information about window size')
	parser.add_argument('-l', action='store', dest='left_size', help='Maximum left size of window')
	parser.add_argument('-r', action='store', dest='right_size', help='Maximum right size of window')
	parser.add_argument('-o', action='store', dest='output', help='Path to output file')
	args = parser.parse_args()
	if not os.path.exists(args.tuple):
		sys.exit("Tuples file doesn't exist")
	if args.output==None:
		sys.exit("You need to set output")
	if args.remove_size and (args.left_size!=None or args.right_size!=None):
		sys.exit("If you set -d option, cannot change size of window")
	if args.left_size!=None:
		if not is_int(args.left_size):
			sys.exit("-l argument is not a integer")
		else:
			left = int(args.left_size)
	else:
		left = None
	
	if args.right_size!=None:
		if not is_int(args.right_size):
			sys.exit('-r argument is not a integer')
		else:
			right = int(args.right_size)
	else:
		right = None
		
	resize_window(args.tuple, args.output, left , right, args.remove_size)

if __name__ == "__main__":
	main()
