##################################
#                                #
# Last modified 2024/08/23       # 
#                                #
# 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 middle_left middle_right outsidelft outsideright outfilename' % sys.argv[0]
        print '\tassumed input format:' 
        print '\t\tpos\tscore' 
        sys.exit(1)

    datafilename = sys.argv[1]
    mleft = int(sys.argv[2])
    mright = int(sys.argv[3])
    oleft = int(sys.argv[4])
    oright = int(sys.argv[5])
    outfilename = sys.argv[6]

    print mleft, mright, oleft, oright

    outfile = open(outfilename, 'w')

    lineslist  = open(datafilename)
    for line in lineslist:
        file = line.strip().split('\t')[0]
        lines = open(file)
        scoreDict = {}
        for LL in lines:
            fields = LL.strip().split('\t')
            pos = int(fields[0])
            score = float(fields[1])
            scoreDict[pos] = score
        insideTotal = 0
        outsideTotal = 0
        for pos in scoreDict.keys():
            if pos >= mleft and pos <= mright:
                insideTotal += scoreDict[pos]
            elif pos <= oleft or pos >= oright:
                outsideTotal += scoreDict[pos]
        FPscore = insideTotal/outsideTotal
        outline = file + '\t' + str(FPscore)
        print outline
        outfile.write(outline+'\n')

    outfile.close()
        
run()

