##################################
#                                #
# Last modified 2017/09/15       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s input readlength outifle' % sys.argv[0]
        print '     note: use this for uniqiely mappable tracks only'
        sys.exit(1)

    input = sys.argv[1]
    readlength = int(sys.argv[2])
    outputfilename = sys.argv[3]

    outfile = open(outputfilename, 'w')

    ChrDict={}
    lineslist = open(input)
    for line in lineslist:
        if line.startswith('#'):
            continue
        fields=line.strip().split('\t')
        chr=fields[0]
        if ChrDict.has_key(chr):
            pass
        else:
            ChrDict[chr] = 0.0
            print chr
        left = int(fields[1])
        right = int(fields[2])
        score = float(fields[3])
        for i in range(right - left):
            ChrDict[chr] += score

    keys=ChrDict.keys()
    keys.sort()

    for chr in keys:
        outfile.write(chr+'\t'+str(ChrDict[chr]/readlength)+'\n')

    outfile.close()

run()

