import sys
import subprocess
import os
from redhawk import *

""" Pipeline the hunter and the pipeline_lower.py. The 
input format is like "python pipeline.py SimuRepBase SimuRepBase.fa sim_out.fa 12 hmmsearch_sim.output proc_id sim.align2.bz2",
which are family(ancestor) name, ancestor file, genome file, anchor length, HMM result file, process id, and .align2 file list.
The final output of this tool is _hmmparse.out generated by HMMparse.py"""


def hunter(chrom_file, anchor_len, proc_id):
    cmd = "make; ./translate " + chrom_file + " " + proc_id + "_chr.hsh " + anchor_len
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();

def pipeline_lower(family_name, RepBase_name, chrom_file, hmmsearch_file, proc_id, align2_filelist):
    filelist = ""
    for i in range(len(align2_filelist)):
        filelist = filelist + align2_filelist[i] + " "
	
    exe = "python pipeline_lower.py %d_"+family_name+" %d_"+RepBase_name+" "+chrom_file+ \
          " %d_"+hmmsearch_file+" %d_"+proc_id+" %d_"+filelist                              # this "filelist" can only contain 1 file for now 
    Objs = []
    for i in range(int(num_family)):
        Objs.append(pbsJobHandler(batch_file = str(i)+"_batch.txt", executable = exe % (i, i, i, i, i)))
    for o in Objs:
        o.submitjob()
    for o in Objs:
        o.wait_on_job()
    for o in Objs:
        o.erase_files()

''' Below is without parallel computing'''
##    cmd = "python pipeline_lower.py %d_"+family_name+" %d_"+RepBase_name+" "+chrom_file+ \
##          " %d_"+hmmsearch_file+" %d_"+proc_id+" %d_"+filelist                              # this "filelist" can only contain 1 file for now
##    for i in range(int(num_family)):
##        cur_cmd = cmd%(i, i, i, i, i)
##        out, err = subprocess.Popen(cur_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();
##	print cur_cmd



num_family = sys.argv[7]
hunter(sys.argv[3], sys.argv[4], sys.argv[6])

pipeline_lower(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[5], sys.argv[6], sys.argv[8:])


