##################################
#                                #
# Last modified 2024/01/12       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import math
from sets import Set

def run():

    if len(sys.argv) < 2:
        print 'usage: python %s config_file list_of_files' % sys.argv[0]
        print '\tthe config file should contain the skeletal elements of the plot; the other plots will be added to those'
        print '\tlist_of_files format: outfilename <tab> wiggle <tab> color1 <tab> color2 <tab> r0 <tab> r1 <tab> +/-'
        print '\tlist all tracks to go into the same file under the same outfilename'
        print '\tnew files will be created for negative-value wiggle tracks with the values flipped'
        print '\tr0 and r1 format: 0.60r'
        sys.exit(1)

    config = sys.argv[1]
    list_of_files = sys.argv[2]

    ConfigLines = []
    linelist = open(config)
    for line in linelist:
        ConfigLines.append(line)

    OutfileDict = {}
    linelist = open(list_of_files)
    for line in linelist:
        if line.strip() == '':
            continue
        fields = line.strip().split('\t')
        group = fields[0]
        filename = fields[1]
        color1 = fields[2]
        color2 = fields[3]
        r0 = fields[4]
        r1 = fields[5]
        sign = fields[6]
        maxScore = 0
        print group, filename
        if sign == '-':
            try:
                lines = open(filename)
            except:
                print 'files not found, skipping', group
                continue
            outfile = open(filename+'.sign_flipped', 'w')
            for line1 in lines:
                if line1.startswith('#'):
                    continue
                fields1 = line1.strip().split('\t')
                outline = fields1[0] + '\t' + fields1[1] + '\t' + fields1[2] + '\t' + str((-1)*float(fields1[3]))
                outfile.write(outline + '\n')
            outfile.close()
            filename = filename+'.sign_flipped'
        try:
            lines = open(filename)
        except:
            print 'files not found, skipping', group
            continue
        for line1 in lines:
            if line1.startswith('#'):
                continue
            fields1 = line1.strip().split('\t')
            score = float(fields1[3])
            maxScore = max(maxScore,int(score))
        if OutfileDict.has_key(group):
            pass
        else:
            OutfileDict[group] = []
        OutfileDict[group].append((filename,color1,color2,r0,r1,maxScore,sign))


    for OF in OutfileDict:
        outfile = open(OF + '.conf', 'w')
        for i in range(ConfigLines.index('</plots>\n')):
            outfile.write(ConfigLines[i])
        for (filename,color1,color2,r0,r1,maxScore,sign) in OutfileDict[OF]:
            outfile.write('\n')
            outfile.write('<plot>' + '\n')
            outfile.write('show    = yes' + '\n')
            outfile.write('file    = ' + filename + '\n')
            outfile.write('z       = 5' + '\n')
            outfile.write('max_gap = 0u' + '\n')
            if sign == '-':
                outfile.write('orientation = in' + '\n')
            outfile.write('fill_under = yes' + '\n')
            if sign == '-':
                outfile.write('fill_color = ' + color2 + '\n')
                outfile.write('color   = ' + color1 + '\n')
            else:
                outfile.write('fill_color = ' + color1 + '\n')
                outfile.write('color   = ' + color2 + '\n')
            outfile.write('min     = 0' + '\n')
            outfile.write('max     = ' + str(maxScore) + '\n')
            outfile.write('r0      = ' + r0 + '\n')
            outfile.write('r1      = ' + r1 + '\n')
            outfile.write('</plot>' + '\n')
            outfile.write('\n')
        outfile.write('</plots>\n')
        outfile.close()

run()

