##################################
#                                #
# Last modified 2019/07/09       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math
import pyBigWig
import numpy as np

def run():

    if len(sys.argv) < 4:
        print 'usage: python %s bigWig chrom.sizes window outputfilename [-int]' % sys.argv[0]
        sys.exit(1)

    doInt = False
    if '-int' in sys.argv:
        doInt = True
    
    bigWig = sys.argv[1]
    chrominfo = sys.argv[2]
    chromInfoList = []
    chromInfoDict = {}
    linelist = open(chrominfo)
    for line in linelist:
        fields = line.strip().split('\t')
        chr = fields[0]
        start = 0
        end = int(fields[1])
        chromInfoList.append((chr,start,end))
        chromInfoDict[chr] = (start,end)
    W = int(sys.argv[3])
    outfilename = sys.argv[4]

    bw = pyBigWig.open(bigWig)

    outfile=open(outfilename,'w')

    for (chr,start,end) in chromInfoList:
        print chr, start, end
        values = np.nan_to_num(bw.values(chr,start,end))
        for i in range(len(values)-W):
            print i
            if i % 10000000 == 0:
                print chr, i, end
            score = np.nanmean(values[i:i+W])
            if doInt:
                score = int(score)
            if score == 0 or np.isnan(score):
                continue
            outline = chr + '\t' + str(i) + '\t' + str(i + W) + '\t' + str(score)
            outfile.write(outline + '\n')

    outfile.close()
   
run()
