##################################
#                                #
# Last modified 2019/08/15       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import pyBigWig

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s config chrom.sizes outputfilename' % sys.argv[0]
        print '\tconfig format: label <tab> bigWig'
        sys.exit(1)

    config = sys.argv[1]

    chrominfo = sys.argv[2]
    chromInfoDict = {}
    linelist = open(chrominfo)
    for line in linelist:
        fields = line.strip().split('\t')
        chr = fields[0]
        start = 0
        end = int(fields[1])
        chromInfoDict[chr] = end

    bigWigList = []
    bigWigLabels = []

    ValueDict = {}

    linelist = open(config)
    for line in linelist:
        fields = line.strip().split('\t')
        label = fields[0]
        bigWig = fields[1]
        bigWigList.append(bigWig)
        bigWigLabels.append(label)
        print label
        bw = pyBigWig.open(bigWig)
        for chr in chromInfoDict.keys():
            if ValueDict.has_key(chr):
                pass
            else:
                ValueDict[chr] = {}
            end = chromInfoDict[chr]
            try:
                values = bw.values(chr,0,end)
                for i in range(end):
                    if ValueDict[chr].has_key(i):
                        pass
                    else:
                        ValueDict[chr][i] = []
                    ValueDict[chr][i].append(values[i])
            except:
                for i in range(end):
                    if ValueDict[chr].has_key(i):
                        pass
                    else:
                        ValueDict[chr][i] = []
                    ValueDict[chr][i].append(0)
                print 'cannot retrieve values', chr, label

    outfilename = sys.argv[3]

    outfile=open(outfilename,'w')

    chromosomes = chromInfoDict.keys()
    chromosomes.sort()

    outline = '#chr\tleft\tright'
    for label in bigWigLabels:
        outline = outline + '\t' + label
    outfile.write(outline + '\n')

    for chr in chromosomes:
        print chr
        end = chromInfoDict[chr]
        for i in range(end):
            outline = chr + '\t' + str(i) + '\t' + str(i + 1)
            for j in range(len(bigWigLabels)):
                outline = outline + '\t' + str(ValueDict[chr][i][j])
            outfile.write(outline.replace('nan','0') + '\n')

    outfile.close()
   
run()
