##################################
#                                #
# Last modified 07/11/2011       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math
from commoncode import *

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s input fieldID outputfilename [-integer] [-float] [-reverse]' % sys.argv[0]
        sys.exit(1)
    
    input = sys.argv[1]
    sortField = int(sys.argv[2])
    outfilename = sys.argv[3]

    doReverse=False
    if '-reverse' in sys.argv:
        doReverse=True
        print 'will sort in decreasing order'

    doInt=False
    if '-integer' in sys.argv:
        doInt=True
        print 'will treat values as integers'
        doFloat=False

    doFloat=False
    if '-float' in sys.argv:
        doFloat=True
        doInt=False
        print 'will treat values as floats'

    LineList=[]

    outfile = open(outfilename,'w')

    lineslist = open(input)
    i=0
    for line in lineslist:
        i+=1
        if i % 1000000 == 0:
            print i, 'lines processed'
        if line[0]=='#':
            continue
        fields=line.strip().split('\t')
        if doInt:
            value=int(fields[sortField])
        elif doFloat:
            value=float(fields[sortField])
        else:
            value=fields[sortField]
        LineList.append((value,line))

    LineList.sort()
    LineList.reverse()

    for (value,line) in LineList:
        outfile.write(line)

    outfile.close()
   
run()
