import sys
import subprocess
import os

""" Pipeline the TEprofiler, the malToSto, HMMer, chunks.cpp and HMM result parser as a whole. 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 TEprofiler(family_name, RepBase_name, align2_filelist, proc_id):
    filelist = ""
    for i in range(len(align2_filelist)):
        filelist = filelist + align2_filelist[i] + " "
    cmd = "python TEprofiler_bz2.py -a " + family_name + " " + RepBase_name + " " + proc_id + " " + filelist
    print cmd
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();
    
def malToSto(proc_id):
#    cmd = "python mal_to_sto.py whole.mal whole.sto"
    cmd = "python mal_to_sto.py " + proc_id + "_whole.mal " + proc_id + "_whole.sto"
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();

def hmmbuild(proc_id): 
    cmd = "module load hmmer; hmmbuild --dna " + proc_id + "_whole.hmm " + proc_id + "_whole.sto"
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();

def chunk(RepBase_name, chrom_file, family_name, proc_id, chunk_proc_id):
    cmd = "make; ./chunks " + chunk_proc_id + "_chr.hsh " + RepBase_name + " " + chrom_file + " " + family_name + " " + proc_id
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();
    

def hmmsearch(output_file, proc_id):
    cmd = "module load hmmer; hmmsearch " + proc_id + "_whole.hmm " + proc_id + "_chunks.fa > " + output_file
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();


def hmmparser(hmms_file, proc_id):
    cmd = "python HMMparse.py " + hmms_file + " " + proc_id
    out, err = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate();


proc_id = sys.argv[5]       # this section is to delete "1_" in "1_2222" for the chunk function to use a common .hsh file
j = 0
while(proc_id[j]!='_'):
    j = j + 1
chunk_proc_id = proc_id[(j+1):]

TEprofiler(sys.argv[1], sys.argv[2], sys.argv[6:], sys.argv[5])
malToSto(sys.argv[5])
hmmbuild(sys.argv[5])
chunk(sys.argv[2], sys.argv[3], sys.argv[1], sys.argv[5], chunk_proc_id)
hmmsearch(sys.argv[4], sys.argv[5])
hmmparser(sys.argv[4], sys.argv[5])
