##################################
#                                #
# Last modified 02/23/2011       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string

try:
    import psyco
    psyco.full()
except:
    print 'psyco not running'

def run():

    if len(sys.argv) < 6:
        print 'usage: python %s peaks peakChrID peakFieldID bed bedChrID outfile' % sys.argv[0]
        sys.exit(1)

    peaks = sys.argv[1]
    peakChrID = int(sys.argv[2])
    peakID = int(sys.argv[3])
    bed = sys.argv[4]
    chrID = int(sys.argv[5])
    outfile = open(sys.argv[6],'w')

    listoflines = open(peaks)
    PeakDict={}
    for line in listoflines:
        if line[0]=='#':
            continue
        fields=line.split('\n')[0].split('\t')
        chr=fields[peakChrID]
        peak=int(fields[peakID])
        if PeakDict.has_key(chr):
            pass
        else:
            PeakDict[chr]=[]
        PeakDict[chr].append(peak)

    listoflines = open(bed)
    BedDict={}
    for line in listoflines:
        if line[0]=='#':
            continue
        fields=line.split('\n')[0].split('\t')
        chr=fields[chrID]
        left=int(fields[chrID+1])
        right=int(fields[chrID+2])
        overlapping=[]
        outline=line.strip()+'\t'
        if PeakDict.has_key(chr):
            for peak in PeakDict[chr]:
                if peak >= left and peak <= right:
                    overlapping.append(peak)
            for peak in overlapping:
                outline=outline+str(peak-left)+','
            if len(overlapping)==0:
                outline=outline+'-,'
        else:
            outline=outline+'-,'
        outfile.write(outline[0:-1]+'\n')
        
    outfile.close()

run()
