#!/usr/bin/ipython
; -*- mode: python -*-

import sys
import os

## This script takes a directory which has a files for each gene that 
## contain the "ortho codes" for the gene. It creates a file for each
## gene that contains the orthologous groups that gene in a part of.

def usage():
	print "find_ortho_groups.ipy\n \
		<directory of ortho codes to search for>\n \
		<orthoMCL groups.txt file>"

if len(sys.argv) != 3:
	usage()
directory = sys.argv[1]
groups_file = sys.argv[2]

!mkdir ortho_byGene
files = !ls {directory}
for file in files:
	gene = file.partition('_')[0]
	f = open(directory + file)
	codes = f.readlines()
	f.close()
	for code in codes:
		clean_code = '"%s"' % code[:-1]
		!grep {clean_code} {groups_file} >> {"./ortho_byGene/" + gene + '.txt'}

fils = !ls ortho_byGene
for fil in fils:
	gene = fil.partition('.')[0]
	!sort {"ortho_byGene/" + fil} | uniq > {"ortho_byGene/" + gene}

!rm ./ortho_byGene/*.txt
