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

import sys
import string
import os

def run():

    if len(sys.argv) < 1:
        print 'usage: python %s wig [-minScore float] [-maxScore float]' % sys.argv[0]
        print '\tUse - for stdin, the file will also take .gz and .bz2 files automatically'
        sys.exit(1)

    input = sys.argv[1]

    doMinScore = False
    if '-minScore' in sys.argv:
        doMinScore = True
        MinScore = float(sys.argv[sys.argv.index('-minScore') + 1])

    doMaxScore = False
    if '-maxScore' in sys.argv:
        doMaxScore = True
        MaxScore = float(sys.argv[sys.argv.index('-maxScore') + 1])

    doStdIn = False
    if input != '-':
        if input.endswith('.bz2'):
            cmd = 'bzip2 -cd ' + input
        elif input.endswith('.gz'):
            cmd = 'zcat ' + input
        else:
            cmd = 'cat ' + input
        p = os.popen(cmd, "r")
    else:
        doStdIn = True

    i=0
    line = 'line'
    while line != '':
        if doStdIn:
            line = sys.stdin.readline()
        else:
            line = p.readline()
        if line == '':
            break
        if line.startswith('#'):
            continue
        i+=1
        fields = line.strip().split('\t')
        chr = fields[0]
        left = int(fields[1])
        right = int(fields[2])
        score = float(fields[3])
        if i == 1:
            currChr = chr
            currLeft = left
            currRight = right
            currScore = score
            continue
        if chr == currChr and left == currRight and score == currScore:
            currRight = right
        else:
            outline = (currChr, currLeft, currRight, currScore)
            currChr = chr
            currLeft = left
            currRight = right
            currScore = score
            if doMaxScore:
                if outline[3] > MaxScore:
                    continue
            if doMinScore:
                if outline[3] < MinScore:
                    continue
            outline = outline[0] + '\t' + str(outline[1]) + '\t' + str(outline[2]) + '\t' + str(outline[3])
            print outline

run()

