##################################
#                                #
# Last modified 01/29/2009       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import math

try:
	import psyco
	psyco.full()
except:
	pass

def run():

    if len(sys.argv) < 6:
        print 'usage: python %s ERANGE.hts chr_field peakfield TSSfile chr_field outfilename' % sys.argv[0]
        sys.exit(1)

    ERANGE = sys.argv[1]
    ERANGE_chrfieldID=int(sys.argv[2])
    ERANGE_peakfieldID=int(sys.argv[3])
    TSSfile = sys.argv[4]
    TSS_chrfieldID=int(sys.argv[5])
    outputfilename = sys.argv[6]

    outfile = open(outputfilename, 'w')

    input_stream = open(TSSfile)
    TSSDict={}
    for line in input_stream:
        fields=line.strip().split('\t')
        chr=fields[TSS_chrfieldID]
        orientation=fields[TSS_chrfieldID-1]
        TSS=int(fields[TSS_chrfieldID+1])
        if TSSDict.has_key(chr):
            TSSDict[chr].append((TSS,orientation))
        else:
            TSSDict[chr]=[]
            TSSDict[chr].append((TSS,orientation))
            
    input_stream = open(ERANGE)
    outfile.write('chr'+'\t'+'peak'+'\t'+'TSS'+'\t'+'distance'+'\n')       
    for line in input_stream:
        if line[0]=='#':
            continue
        fields=line.strip().split('\t')
        peak=int(fields[ERANGE_peakfieldID])
        chr=fields[ERANGE_chrfieldID]
        distance=1000000000000000000
        currentTSS=(0,'')
        if TSSDict.has_key(chr):
            pass
        else:
            continue
        for (TSS,orientation) in TSSDict[chr]:
            if math.fabs(TSS-peak) < distance:
                distance=math.fabs(TSS-peak)
                currentTSS=(TSS,orientation)
        if currentTSS[1]=='+':
            distance=peak-currentTSS[0]
        if currentTSS[1]=='-':
            distance=currentTSS[0]-peak
        outfile.write(chr+'\t'+str(peak)+'\t'+str(currentTSS[0])+'\t'+str(distance)+'\n')       
    
    outfile.close()

run()

