#!/usr/bin/env python
import re, os, sys, shutil
from math import *   
from string import *
from optparse import OptionParser
import operator
	
def main(argv):
	parser = OptionParser()
	parser.add_option("-i", "--islandsummary", action="store", type="string", dest="islandsummary", metavar="<file>", help="island summary file")
	parser.add_option("-p", "--pvalue", action="store", type="float", dest="pvalue", metavar="<float>", help="pvalue, default value -1", default=-1)
	parser.add_option("-q", "--FDR", action="store", type="float", dest="fdr", metavar="<float>", help="FDR, default value -1", default=-1)
	parser.add_option("-o", "--outfile", action="store", type="string", dest="out_file", metavar="<file>", help="File storing significant islands given pvalue or FDR")
	
	(opt, args) = parser.parse_args(argv)
	if len(argv) < 6:
        	parser.print_help()
        	sys.exit(1)
		
	inputfile = open(opt.islandsummary,'r');
	outfile = open(opt.out_file, 'w');
	total =0;
	totalislands = 0;
	
	if opt.pvalue > 0 and opt.fdr < 0 : 
		for line in inputfile:
			if not re.match("#", line):
				line = line.strip()
				sline = line.split()
				if atof(sline[5]) <= opt.pvalue:
					totalislands += 1;
					total += atoi(sline[3]);
					outfile.write('\t'.join(sline)+'\n');
		print "Given p le ",  opt.pvalue, ",  there are ", totalislands, " significant islands. Total number of reads on significant islands is ",  total;
	elif opt.fdr > 0 and opt.pvalue < 0:
		for line in inputfile:
			if not re.match("#", line):
				line = line.strip()
				sline = line.split()
				if atof(sline[7]) <= opt.fdr:
					total += atoi(sline[3]);
					totalislands += 1;
					outfile.write('\t'.join(sline)+'\n');
		print "Given FDR ",  opt.fdr, ",  there are ", totalislands, " significant islands. Total number of reads on significant islands is ",  total;
	else:
		print "Command line parameter choices are wrong, please provide either a valid pvalue threshold or a valid FDR threshold."
	
	inputfile.close()
	outfile.close()
	
	
	
if __name__ == "__main__":
	main(sys.argv)