#! /usr/bin/env python 
###################################
#    Davi Ortega 4/21/2011 
###################################
import sys
import bitk
if '-h' in sys.argv:
	print 'Exclude sequences above some identity level\nSintax: xclud_ident #Ident_cutoff msa.fa \n IT MUST BE ALIGNED'
	sys.exit()

print 'Reading sequences'
ID_cut = float(sys.argv[1])  
seq_dic, seq_list = bitk.fastareader(sys.argv[2],'r')

ID = 0
xclud = []

print 'Calculations'

for seq1 in seq_list:
	if seq1 not in xclud:
		print 'Working on ' + seq1
		for seq2 in seq_list:
			if (seq2 not in xclud) and (seq1 != seq2):
				error = 0
				total = 0
				for i in range(len(seq_dic[seq1])):
					try:
						if seq_dic[seq1][i] != seq_dic[seq2][i]:
							error += 1
						if 1 - (error/float(len(seq_dic[seq1].replace('-','')) )) < ID_cut:
							break
						if i == len(seq_dic[seq1])-1:
							xclud.append(seq2)
							print 'Excluding ' + seq2
					except IndexError:
						print seq1
						print seq_dic[seq1]
						print len(seq_dic[seq1])
						print seq2
						print seq_dic[seq2]
						print len(seq_dic[seq2])
						print i
						sys.exit()
						

output = ''
for seq in seq_list:
        if seq not in xclud:
                output += '>' + seq + '\n' + seq_dic[seq] + '\n'

outfile = open(sys.argv[2][:-2] + sys.argv[1] + '.fa','w')
outfile.write(output)
outfile.close()



