##################################
#                                #
# Last modified 2025/05/27       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math
from sets import Set

def run():

    if len(sys.argv) < 6:
        print 'usage: python %s list_of_profiles minScoreleft minScoreright maxScoreLeft maxScoreRight outfilename' % sys.argv[0]
        print '\tassumed input format:' 
        print '\t\t#pos    1-meth  meth    N_sites' 
        print '\tthe meth score will be used' 
        sys.exit(1)

    datafilename = sys.argv[1]
    minScoreLeft = int(sys.argv[2])
    minScoreRight = int(sys.argv[3])
    maxScoreLeft = int(sys.argv[4])
    maxScoreRight = int(sys.argv[5])
    outfilename = sys.argv[6]

    print minScoreLeft, minScoreRight, maxScoreLeft, maxScoreRight

    outfile = open(outfilename, 'w')
    outline = '#file\tminScore\tmaxScore'
    outfile.write(outline+'\n')

    lineslist  = open(datafilename)
    for line in lineslist:
        file = line.strip().split('\t')[0]
        print file
        lines = open(file)
        scoreDict = {}
        for LL in lines:
            if LL.startswith('#'):
                continue
            fields = LL.strip().split('\t')
            pos = int(fields[0])
            score = float(fields[2])
            scoreDict[pos] = score
        maxScore = 0
        minScore = 10000000000000000
        for pos in scoreDict.keys():
            if pos >= minScoreLeft and pos <= minScoreRight:
                if scoreDict[pos] < minScore:
                    minScore = scoreDict[pos]
            if pos >= maxScoreLeft and pos <= maxScoreRight:
                if scoreDict[pos] > maxScore:
                    maxScore = scoreDict[pos]
        outline = file + '\t' + str(minScore) + '\t' + str(maxScore)
        outfile.write(outline+'\n')

    outfile.close()
        
run()

