##################################
#                                #
# Last modified 2018/01/28       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import os

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s wig chrom.sizes minScore' % sys.argv[0]
        print '\tthe script will print to stdout by default'
        sys.exit(1)

    wig = sys.argv[1]
    chromsizes = sys.argv[2]
    score = float(sys.argv[3])

    chromSizeDict = {}
    linelist = open(chromsizes)
    for line in linelist:
        fields = line.strip().split('\t')
        chr = fields[0]
        size = int(fields[1])
        chromSizeDict[chr] = size

    SeenChrDict = {}

    if wig.endswith('.bz2'):
        cmd = 'bzip2 -cd ' + wig
    elif wig.endswith('.gz'):
        cmd = 'gunzip -c ' + wig
    else:
        cmd = 'cat ' + wig
    p = os.popen(cmd, "r")
    line = 'line'
    currentChr = ''
    InMappable = False
    while line != '':
        line = p.readline()
        if line == '':
            break
        if line.startswith('#'):
            continue
        fields = line.strip().split('\t')
        chr = fields[0]
        SeenChrDict[chr] = 1
        if currentChr == '':
            currentChr = chr
            currentLeft = 0
            currentRight = 0
        left = int(fields[1])
        right = int(fields[2])
        M = float(fields[3])
        if chr != currentChr:
            print currentChr + '\t' + str(currentLeft) + '\t' + str(chromSizeDict[currentChr])
            currentChr = chr
            currentLeft = 0
            currentRight = 0
        if M >= score:
            currentRight = left
            if InMappable:
                pass
            else:
                if currentRight > 0:
                    print currentChr + '\t' + str(currentLeft) + '\t' + str(currentRight)
            InMappable = True
        if M < score:
            if InMappable:
                currentLeft = left
                currentRight = right
            else:
                currentRight = right
            InMappable = False
    print currentChr + '\t' + str(currentLeft) + '\t' + str(chromSizeDict[currentChr])

    for chr in chromSizeDict.keys():
        if SeenChrDict.has_key(chr):
            pass
        else:
            print chr + '\t' + str(0) + '\t' + str(chromSizeDict[chr])

run()

