##################################
#                                #
# Last modified 01/06/2013       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string

def run():

    if len(sys.argv) < 4:
        print 'usage: python %s overlapped-peaks.txt maxIDR [local | IDR] outfile' % sys.argv[0]
        print 'Expected format:'
        print '"chr1" "start1" "stop1" "sig.value1" "chr2" "start2" "stop2" "sig.value2" "idr.local" "IDR"'
        print '"1" "chrUn_random" 12140 12370 4.76735050583428 "chrUn_random" 12099 12599 3.49622818163576 0.571945966982361 0.247619937589086'
        sys.exit(1)

    peaks = sys.argv[1]
    maxIDR = float(sys.argv[2])
    IDR = sys.argv[3]
    if IDR == 'local':
        IDRfieldID = 9
    if IDR == 'IDR':
        IDRfieldID = 10

    outfile = open(sys.argv[4],'w')

    listoflines = open(peaks)
    for line in listoflines:
        if line.strip().endswith('"IDR"'):
            continue
        fields=line.strip().replace('"','').split(' ')
        if float(fields[IDRfieldID]) > maxIDR:
            continue
        outline = line.replace('"','').replace(' ','\t')
        outfile.write(outline)
        
    outfile.close()

run()
