##################################
#                                #
# Last modified 2019/05/14       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
from sets import Set
import gzip
import math

def run():

    if len(sys.argv) < 2:
        print 'usage: python %s table fraction_difference outputfilename' % sys.argv[0]
        print '\ttable format:' 
        print '\tchr\tleft\tright\tmappability_1\tmappability_2' 
        sys.exit(1)
    
    table = sys.argv[1]
    fraction = float(sys.argv[2])
    outfilename = sys.argv[3]

    outfile = open(outfilename, 'w')

    if table.endswith('.gz'):
        linelist = gzip.open(table)
    else:
        linelist = open(table)
    for line in linelist:
        fields = line.strip().split('\t')
        M1 = float(fields[3])
        M2 = float(fields[4])
        if max(M1,M2) == 0:
            continue
        if math.fabs((M1 - M2)/max(M1,M2)) > fraction:
            outfile.write(line)

    outfile.close()
            
run()
