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

import sys
import string
import os

def run():

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

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

    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 = ''
    while line != '':
        line = p.readline()
        if line == '':
            break
        if line.startswith('#'):
            continue
        fields = line.strip().split('\t')
        chr = fields[0]
        left = int(fields[1])
        right = int(fields[2])
        if chr != currentChr:
            if currentChr == '':
                pass
            else:
                print currentChr + '\t' + str(currentLeft) + '\t' + str(currentRight)
            currentChr = chr
            currentLeft = ''
            currentRight = ''
        M = float(fields[3])
        if M < score:
            continue
        if left == currentRight:
            currentRight = right
        else:
            if currentLeft != '':
                print currentChr + '\t' + str(currentLeft) + '\t' + str(currentRight)
            currentChr = chr
            currentLeft = left
            currentRight = right
    print currentChr + '\t' + str(currentLeft) + '\t' + str(currentRight)

run()

