##################################
#                                #
# Last modified 03/14/2013       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import math

def run():

    if len(sys.argv) < 6:
        print 'usage: python %s input fieldID(s) [all | either] minValue maxValue outfilename' % sys.argv[0]
        print '\tfieldID(s) separated by comma, use the all | either option to specify whether the threshold should apply to all fields or only to at least one'
        sys.exit(1)
    
    input = sys.argv[1]
    fieldIDs = []
    fields = sys.argv[2].split(',')
    for ID in fields:
        fieldIDs.append(int(ID))
    AllOrEither = sys.argv[3]
    minValue = float(sys.argv[4])
    maxValue = float(sys.argv[5])
    outfilename = sys.argv[6]

    outfile = open(outfilename, 'w')

    listoflines = open(input)
    for line in listoflines:
        if line.startswith('#'):
            continue
        fields=line.strip().split('\t')
        values = []
        try:
            for ID in fieldIDs:
                values.append(float(fields[ID]))
        except:
            continue
        if AllOrEither == 'all':
            if min(values) >= minValue and min(values) <= maxValue:
                outfile.write(line)
        if AllOrEither == 'either':
            if max(values) >= minValue and max(values) <= maxValue:
                outfile.write(line)

    outfile.close()
   
run()
