##################################
#                                #
# Last modified 08/12/2013       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s input p-value outputfilename [-padj]' % sys.argv[0]
        print '       Note: the script relies on the DESeq output having been passed through the fixDESeqOuput.py script, i.e. tab-delimited and with a header line starting with the # sign'
        sys.exit(1)
    
    input = sys.argv[1]
    MaxPValue = float(sys.argv[2])
    outfileUp = open(sys.argv[3] + '-up', 'w')
    outfileDown = open(sys.argv[3] + '-down', 'w')

    doPAdj = False
    if '-padj' in sys.argv:
        doPAdj = True

    linelist = open(input)
    for line in linelist:
        fields=line.strip().split('\t')
        if line.startswith('#'):
            outfileUp.write(line)
            outfileDown.write(line)
            if doPAdj:
                pvalueFieldID = fields.index('padj')
            else:
                pvalueFieldID = fields.index('pval')
            foldChangeFieldID = fields.index('foldChange')
            continue
        if fields[pvalueFieldID] == 'NA':
            continue
        pval = float(fields[pvalueFieldID])
        if pval <= MaxPValue:
            foldChange = fields[foldChangeFieldID]
            if foldChange == 'Inf':
                outfileUp.write(line)
            elif foldChange == '-Inf':
                outfileDown.write(line)
            else:
                if float(foldChange) > 1:
                    outfileUp.write(line)
                if float(foldChange) < 1:
                    outfileDown.write(line)

    outfileUp.close()
    outfileDown.close()
   
run()