#!/usr/bin/env python
import sys
import os
import time
import fileinput

# set up the path to the script.
# not necessary to specify manually
BINPATH=os.path.dirname(sys.argv[0])+'/';


# defaultprocesssamoption='-g 100 -i -u 0.05 '

#-------code-----

if len(sys.argv)<2:
  print('Usage: runcem.py {processsam and isolassocem options} <.instance | .sam | .bam | ->  \n\n');
  print('----------processsam options:---------------\n\n');
  sys.stdout.flush();
  os.system(BINPATH+'processsam');
  print('\n\n----------isolasso options:---------------\n\n');
  sys.stdout.flush();
  os.system(BINPATH+'isolassocem');
  sys.exit();

# default output file
prefix='isolasso.instance';
hasooption=False;

for i in range(1,len(sys.argv)-1):
  if i<len(sys.argv)-1:
    if sys.argv[i]=='-o' or sys.argv[i]=='--prefix':
      prefix=sys.argv[i+1];
      hasooption=True;


commandlineoption=' --useem ';
for i in range(1,len(sys.argv)-1):
  commandlineoption=commandlineoption+' '+sys.argv[i];

    

# the following command is the default processsam options
processsamoptions=commandlineoption;


time1=time.time();

instancefile=sys.argv[-1];

if instancefile.endswith('.sam') or instancefile=='-':
  samproccmd=BINPATH+'processsam '+processsamoptions+' '+instancefile;
  print('Processing sam file. Command: '+samproccmd);
  os.system(samproccmd);
  # for SAM file, the default instance file by processsam is instancefile.instance
  if hasooption:
    instancefile=prefix+".instance";
  else:
    instancefile=instancefile+'.instance';
elif instancefile.endswith('.bam'):
  # check if samtools is within the system path
  if os.system('which samtools')!=0:
    print('Error: samtools required for processing .bam file.');
    sys.exit();
  samproccmd='samtools view '+instancefile+ ' | '+BINPATH+'processsam '+processsamoptions;
  if not hasooption:
    samproccmd=samproccmd + ' -o '+ instancefile;
  samproccmd=samproccmd+' - ';
  print('Processing sam file. Command: '+samproccmd);
  os.system(samproccmd);
  # for BAM file, the default is isolasso.instance. Don't use default here
  if hasooption:
    instancefile=prefix+".instance";
  else:
    instancefile=instancefile+'.instance';
  

print('Instance file:'+instancefile);


binary = BINPATH + "isolassocem "
command=binary+commandlineoption+" "+instancefile;
os.system(command);

# the default output of isolasso is instancefile.pred
if hasooption:
  outputfile=prefix+'.pred';
else:
  outputfile=instancefile+'.pred';

cvtcmd=BINPATH+'pred2gtf '+outputfile + ' | ' + BINPATH+ 'sortgtf -o '+outputfile+'.gtf -';

print('Convert command: '+cvtcmd);

os.system(cvtcmd);

time2=time.time();

print('Total running time: '+str((time2-time1))+' seconds');
