##################################
#                                #
# Last modified 05/06/2010       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys

try:
	import psyco
	psyco.full()
except:
	pass

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s label inputfilename outfilename [-chr chromosome]' % sys.argv[0]
        print 'Note: this script does not work for spliced reads, use it only for single-end non-gapped read alignments' 
        sys.exit(1)

    label = sys.argv[2]
    inputfilename = sys.argv[2]
    outputfilename = sys.argv[3]
    outfile = open(outputfilename, 'w')
    doChr=False
    if '-chr' in sys.argv:
        doChr=True
        chromosome=sys.argv[sys.argv.index('-chr')+1]
        print 'will consider only', chromosome

    outline = 'track name="' + label + '" visibility=4 itemRgb="On"'
    outfile.write(outline + '\n')

    lineslist = open(inputfilename)
    i=0
    for line in lineslist:
        i+=1
        if i % 1000000 == 0:
            print i, 'lines processed'
        fields = line.strip().split('\t')
        chr=fields[2]
        if doChr and chr!= chromosome:
            continue
        start=int(fields[3])
        stop=start+len(fields[4])
        orientation=fields[1]
        ID=fields[0]
        if orientation=='+':
            RGB='255,0,0'
        if orientation=='-':
            RGB='0,0,255'
        multi=int(fields[6])
        scaling=1000
        if multi!=0:
            RGB='0,0,0'
            scaling=int(1000.0/multi)
        outline= chr+'\t'+str(start)+'\t'+str(stop)+'\t'+ID+'\t'+str(scaling)+'\t'+orientation+'\t'+'-\t-\t'+RGB+'\t'+'1\t'+str(stop-start)+'\t'+'0\n'
        outfile.write(outline)
    outfile.close()

run()

