#!/usr/bin/env python3

import birchenv
import birchscript
import os
import os.path
import subprocess
import sys
import re
import shutil

'''
blast2gi.py - Given a BLAST output file, retrieve a list of GI numbers corresponding
   to BLAST hits.

Synopsis: blast2gi.py infile outfile 

  $1 BLAST output in pairwise format
  $2 output from blast_formatter in csv tabular format
  
@modified: June 9, 2014
@author: Brian Fristensky
@contact: frist@cc.umanitoba.ca  
'''


blib = os.environ.get("BIRCHPYLIB")
sys.path.append(blib)

from birchlib import Birchmod
from birchlib import Argument

PROGRAM = "blast2gi.py : "
USAGE = "\n\tUSAGE: blast2gi.py infile outfile"

BM = Birchmod(PROGRAM, USAGE)



class Parameters:
    """
      	Wrapper class for command line parameters
      	"""
    def __init__(self):
        """
     	  Initializes arguments:
     		IFN=""
     		DESTINATION=""
     		OFN=""
     		PID=""
     	  Then calls read_args() to fill in their values from command line
          """
        self.IFN = ""
        self.DESTINATION = "textedit"
        self.OFN = ""
        self.PID = str(os.getpid())
        self.read_args()

    def read_args(self):
        """
        	Read command line arguments into a Parameter object

        	"""

        infile = Argument("", str, BM)
        #dest = Argument("-d", str, BM)
        outfile = Argument("", str, BM)

        infile.set_position(1)
        outfile.set_position(len(sys.argv) - 1)
	    #outfile.set_optional()
	    
        try:
            self.IFN = infile.fetch()
            self.OFN = outfile.fetch()
            #self.DESTINATION = dest.fetch()	

        except:
            BM.printusage()

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def RetrieveTable(BLASTFN,OFN):
    """ 
 """
 
    # Get the RID number from the BLAST output
    h_BLASTFILE  = open(BLASTFN, "r")
    RID=''
    line = h_BLASTFILE.readline()
    while ( line != '' and RID == '' ) :
        POSN=line.find('RID: ')
        if POSN >= 0 :
            RID = str(line[5:]).strip()
        line = h_BLASTFILE.readline()
    h_BLASTFILE.close()
    print 'RID: ' + RID


    # Run blast_formatter to retrieve a table of fields from the blast report.
    #p = subprocess.Popen(['blast_formatter', '-rid='+RID, '-outfmt=10 sseqid sgi slen evalue', '-out='+OFN])
    p = subprocess.Popen(['blast_formatter', '-rid='+RID, '-outfmt=7 sgi', '-out='+OFN])
    p.wait()

   
#======================== MAIN PROCEDURE ==========================
def main():
    """
        Called when not in documentation mode.
        """
	
    # Read parameters from command line
    P = Parameters ()
	
    # Retrieve GI numbers from NCBI to outfile
    RetrieveTable(P.IFN,P.OFN)
	   
    BM.exit_success()

if (BM.documentor() or "-test" in sys.argv):
    pass
else:
    main()





