#! /opt/gensoft/exe/blastTaxoAnalysis/1.0/venv/bin/python2.7

# Corinne Maufrais
# Institut Pasteur, Groupe Logisiels et Banques de sonnees
# maufrais@pasteur.fr
#
# blast2genoclass the one-line description of Blast program  

# version 1.0


import os, sys, getopt
from subprocess import *

import Golden
#os.environ['GOLDENDATA'] = "/mount/banques/prod/index/golden"

try:
    GOLDENDATA =  os.environ['GOLDENDATA']
except:
    GOLDENDATA = "/local/databases/index/golden"
    os.environ['GOLDENDATA'] = GOLDENDATA

try:
    LIB = os.environ['BLAST2TC_LIB']
except:
    LIB = '/usr/local/bin'

if LIB not in sys.path:
    sys.path.append( LIB )

try:
    TABLE = os.environ['TAXOBDBDATA']
except:
    TABLE = '/local/databases/rel/current/taxodb/bdb/'

TAXODB_BDB = 'taxodb.bdb'

import xml.sax, sys, copy
from xml.sax.handler import ContentHandler

import BlastParser 
import genoGd
import extractfasta

####################    blast2genoclass.py

class ParserError:
    def __init__(self,err):
        self.err = err

    def __repr__(self):
        return "[ParserError] " + self.err

class ParserWarning:
    def __init__(self,err):
        self.err = err

    def __repr__(self):
        return "[ParserWarning] " + self.err



# organisme name only
def parseUniprot( flatFile ):
    """
    parse uniprot or embl like flat file
    """
    taxId= ''
    taxoLight = ''
    orgName = ''
    description = ''
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:2].strip()
        value = line[5:-1]
        if tag == 'OS':
            orgName += value
        elif tag == 'DE':
            description += value
        elif tag == 'OC':
            taxoLight += value
        elif tag == 'OX':
            taxId += value
        elif tag in ['RN', 'DR','CC', 'FH', 'SQ']:
            return orgName, taxId, taxoLight, description
    return orgName, taxId, taxoLight, description

def parseUniprotSeq( flatFile, format ):
    """
    parse uniprot or embl like flat file
    """
    ID= ''
    SEQ = ''
    DE = ''
    seqVu = False
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:2].strip()
        value = line[5:]
        if tag == 'ID':
            ID += value.split()[0]
        elif tag == 'DE':
            DE += value
        elif tag == 'SQ' and not seqVu:
            seqVu = True
        elif seqVu:
            SEQ += value.replace(' ' , '' )
    if format =='fasta':
        sequence = '>%s %s\n' % (ID, DE)
        i = 0
        while i < len(SEQ):
            sequence += SEQ[i:i+80] +'\n'
            i+=80
        return sequence
    elif format =='raw':
        return SEQ
    



def parseGenbank( flatFile ):
    """
    parse genbank like flat file
    """
    description = ''
    taxId= ''
    taxoLight = ''
    orgName = ''
    taxoL = False
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:12].strip()
        value = line[12:]
        if tag == 'ORGANISM': # one line
            orgName += value
            taxoL=True
        elif tag == 'DEFINITION':
            description += value
        elif taxoL and not tag: # multiple line without tag
            taxoLight += value
        elif tag == 'TaxID': # gi number
            taxId += value
        elif tag in ['REFERENCE','COMMENT', 'FEATURES', 'ORIGIN']:
            return orgName, taxId, taxoLight, description
        elif not tag: # fin taxonomy
            taxoL = False
    return orgName, taxId, taxoLight, description

def parseGenbankSeq( flatFile, format ):
    """
    parse genbank like flat file
    """
    ID= ''
    SEQ = ''
    DE = ''
    seqVu = False
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:12].strip()
        value = line[12:]
        if tag == 'LOCUS':
            ID += value.split()[0]
        elif tag == 'DEFINITION':
            DE += value
        elif tag == 'ORIGIN' and not seqVu:
            seqVu = True
        elif seqVu:
            SEQ += line[10:].replace(' ' , '' )
    if format =='fasta':
        sequence = '>%s %s\n' % (ID, DE)
        i = 0
        while i < len(SEQ):
            sequence += SEQ[i:i+80] +'\n'
            i+=80
        return sequence
    elif format =='raw':
        return SEQ
    
    
def parse( flatFile, seqOnly, format ):
    """
    parse db flat file ( uniprot, embl, genbank) 
    """
    if flatFile[:2] == 'ID':
        if seqOnly:
            return parseUniprotSeq( flatFile, format )
        else:
            return parseUniprot( flatFile )
    elif flatFile[:5] == 'LOCUS':
        if seqOnly:
            return parseGenbankSeq( flatFile, format )
        else:
            return parseGenbank( flatFile )
    if seqOnly:
        return ''
    return '','','',''

class DBRecord: 
    def __init__( self , database ):
        """
        Holds informations from a db flat file (uniprot, embl, genbank)
        """
        self.database = database
        self.taxId = None
        self.classification = None
        self.species = None
        self.accession = None
        
    def exist( self ): #### new 18/11/10
        return self.classification != None or self.species != None or self.accession != None

class Blast2GenoClassError:
    def __init__( self, err ):
        self.err = err

    def __repr__( self ):
        return "[Blast2GenoClassError] " + self.err

##############################################################################
#
#            Golden
#
##############################################################################



def doGolden( db,ac, seqOnly=False, format='fasta' ):
    ########################### db ref
    if db in[ 'sp', 'sw','swissprot','tr', 'trembl']:
        db = 'uniprot'
    elif db in ['emb', 'dbj']:
        db = 'embl'
    elif db in ['gb']:
        db = 'genbank'
    elif db in ['gp']:
        db = 'genpept'
    elif db in ['ref']:
        db = 'refseq'
    #elif db in ['pir','pdb','tpg', 'tpe', 'tpd', 'prf']:
    #    return '','',''
    try:
        flatFile = Golden.access(db,ac)
    except IOError:
        return '','','',''
    if flatFile:
        return parse( flatFile, seqOnly, format ) #orgName, taxId, taxoLight
    else:
        return '','','',''
    

##############################################################################
#
#            TaxoDB:  genomic annotation --> rank, genomic function
#
##############################################################################


def extractDBrecord( blastHitRecord, allDBRecord ):
    db, acc = blastHitRecord.extractDBinfo()
    if not acc or not db:
        print >>sys.stderr, Blast2GenoClassError ( 'Hit information not well parsed: %s ' % blastHitRecord.comment )
	return None, allDBRecord
    if allDBRecord.has_key( acc ):
        if not blastHitRecord.hitDef:
            blastHitRecord.hitDef = allDBRecord[acc].description
        return allDBRecord[acc], allDBRecord
    
    acc = acc.split('.')[0]
    ## extract db and acc from blast
    dbRecord = None        
    try:
        # species name extraction from blast pairwise info
        orgName = blastHitRecord.comment.split('[')[1].split(']')[0]
    except:
        orgName, taxId, taxoLight, description  = doGolden( db,acc )
############ Mettre l'acc en error pour ne par refaire un golden
        if not orgName:
            return None, allDBRecord
        
        dbRecord = DBRecord( db )
        dbRecord.accession = acc
        dbRecord.taxId = taxId
        dbRecord.classification = taxoLight
        dbRecord.species = orgName
        dbRecord.description = description
        if not blastHitRecord.hitDef:
            blastHitRecord.hitDef = description
    
    taxoFull = osVSocBDB.get( str(orgName) )
    if not taxoFull:
        orgName =  orgName.split('(')[0].strip()
        taxoFull = osVSocBDB.get( str(orgName) )
        if not taxoFull:
            orgName =  orgName.split('.')[0].strip()
            taxoFull = osVSocBDB.get( str(orgName) )
            if not taxoFull:
                if dbRecord:
                    allDBRecord[ acc ] = dbRecord
                    return dbRecord, allDBRecord
                else:
                    return None, allDBRecord
    if not dbRecord:
        dbRecord = DBRecord( db )
        dbRecord.accession = acc
        dbRecord.species = orgName
    if taxoFull:
        dbRecord.classification = taxoFull
    
        fld = dbRecord.classification.split(';')
        if fld[-1] == '':
            dbRecord.classification = ';'.join( fld[:-1])
        
        fld = dbRecord.classification.split(';')
        name, rank = extractRank( fld[0].strip() )
        if name == 'cellular organisms':
            oc = ';'.join( fld[1:] )
            dbRecord.classification = oc.strip()
    allDBRecord[ acc ] = dbRecord
    
    return dbRecord, allDBRecord

def extractRank( node ):
    rank = ''
    fld = node.split('(')
    name = fld[0].strip()
    if len (fld) > 1:
        rank = fld[1].split(')')[0].strip()
    return name, rank

def _extractSPProt(blastHitRecord):
    prot = 'errorSP'
    fld = blastHitRecord.hitDef.split('SubName: Full=')
    if len(fld) > 1:
        prot = fld[1].split(';')[0]
    else:
        fld2 = blastHitRecord.hitDef.split('RecName: Full=')
        if len(fld2) > 1:
            prot = fld2[1].split(';')[0]
    return prot

def _extractDBProt(blastHitRecord):
    prot = 'errorDB'
    fld = blastHitRecord.hitDef.split(',')
    if fld:
        fld2=fld[0].split(' ')
        if len(fld2) > 1:
            prot = ' '.join(fld2[1:])
    return prot

def extractProt( blastHitRecord ):
    if 'Full=' in blastHitRecord.hitDef:
        return _extractSPProt(blastHitRecord)
    else:
        return _extractDBProt(blastHitRecord)

################################################
#
#   Output: split blast, query name, fasta seqRef
#   Verbose: hsp by blast, hsp by seqref 
#
################################################
def outPutFile( prot, vprot, hits=[], blastoutput=True, format='m0', queryoutput=True, seqRefOut=True ):
    if prot == 'noHit':
        return
    prot = prot.replace('/', '-').replace(' ', '-').replace(':', '').replace('(' ,'_').replace(')' ,'_').replace('*', '_').replace('?', '_')
    if blastoutput:
        if format == 'm7':
            fhoutbl = open('%s.xml' % prot, 'w')
        else:
            fhoutbl = open('%s.blast' % prot, 'w')
    if queryoutput:
        fhoutqry = open('%s.qry' % prot, 'w') # liste des query
    
    if seqRefOut and hits:
        # hits = [ [ (blastHitRecord, dbRecord, blastRecord),... ],... ]   liste de hits par blast (qry diff)  pour chaque acc max, 
        listOfdb = [(ht[0][1].accession, ht[0][1].database) for ht in hits]
        allSeq = ''
        for acc, db in listOfdb:
            fastaSeq = doGolden(db,acc, seqOnly=True, format = 'fasta')
            allSeq += fastaSeq
        squizzFh = open ('%s.dbfasta' % prot, 'w')
        print >>squizzFh, allSeq
        squizzFh.close()
            
    blr = '' #init if error
    for blr in vprot['record']:
        if blastoutput:
            if format == 'm0':
                BlastParser.PairwiseBlastPrinter( blr['blastrecord'], fhoutbl )
            if format == 'm7':
                BlastParser.XMLBlastPrinter( blr['blastrecord'], fhoutbl )
        if queryoutput:
            print >>fhoutqry, blr['blastrecord'].queryDef
        
    if blastoutput:
        if format == 'm0' and blr:
            print >>fhoutbl, '  Database: %s version' % blr['blastrecord'].database.capitalize()
            fhoutbl.close()
    if queryoutput: 
        fhoutqry.close()        


def verboseOutFile( verboseoutfh, blastRecord, perHit, prot, protHits, hspOutMode = 0 , all=False ):
    """ display hsps info by blast"""
    if all:
        print >>verboseoutfh, "%2.2f%%\t%s" % ( perHit, prot )
    else:
        print >>verboseoutfh, "\n** %s (%s letters):\t%2.2f%%\t%s\n" % ( blastRecord.queryDef,blastRecord.queryLength, perHit, prot )
        print >>verboseoutfh, 'Number of hits: %s' % len( protHits )
        for i in range( len(protHits) ):
            hit = protHits[i][0]
            print >>verboseoutfh, "\nHit: ", i+1
            print >>verboseoutfh, "Database sequence's species: %s - %s (%s letters)" % (protHits[i][1].accession, protHits[i][1].species, hit.hitLength)
            print >>verboseoutfh, 'Number of hsp: %s\n' % len(hit.hspS)
            hspS =copy.deepcopy( hit.hspS )
            for hsp in extractBestHSPs( hspS, hspOutMode, [] ):
                printHsp( verboseoutfh, hsp )

def verboseOutFileBestAcc( verboseoutfh, blastRecord, hspS ):
    """ display hsp info by seqref"""
    print >>verboseoutfh, 'Query: %s (%s letters)' % (blastRecord.queryDef, blastRecord.queryLength)
    print >>verboseoutfh, 'Number of hsp: %s' % len(hspS)
    for hsp in hspS:
        #printHsp( sys.stdout, hsp )
        printHsp( verboseoutfh, hsp )

def _blastScoreVsColor( val ):
    if 0 <= val < 50:
        return 'blue'
    elif  50 <= val < 100:
        return 'grey'
    elif  100 <= val <150:
        return 'orange'
    elif  150 <= val < 200:
        return 'green'
    elif  200 <= val:
        return 'red'
    else:
        return 'black'

def plot( pictureFileName, p_all, sizeX = 700, typep='png', expend = False):
    """ picture output """
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    if expend:
        gdPlot = genoGd.genoGD( sizeX = sizeX, nbQuery = p_all['n_hsp']*2 )
    else:
        gdPlot = genoGd.genoGD( sizeX = sizeX, nbQuery = p_all['n_qry']*2 )
    gdPlot.plotSeq( seqlen=p_all['dbSeq'][1] , start=0, stop=sizeX, header = p_all['dbSeq'][0].accession, color = 'red', up=True )
    gdPlot._nbligneP()
    rpt = float(sizeX) / p_all['dbSeq'][1]
    nbhit = 0
    for blastRecord, hspSs_hp, hspSs_hm in p_all['hit']:
        head = True
        if len(blastRecord.queryDef)<= 10:
            header = blastRecord.queryDef
        else:   
            header = blastRecord.queryDef[0:10]+'..'
        hspSs = hspSs_hp + hspSs_hm
        for h in hspSs_hp:
            if h.hspHitFrom and h.hspHitTo and str(h.hspExpect):
                gdPlot.plotHit(int(h.hspHitFrom*rpt), int(h.hspHitTo*rpt), header, _blastScoreVsColor(h.hspExpect), head=head)
                #gdPlot.plotHit(int(h.hspHitFrom*rpt), int(h.hspHitTo*rpt), header, 'red', head=head)
                head = False
                nbhit +=1
            if expend:
                gdPlot._nbligneP()
        gdPlot._nbligneP()
        for h in hspSs_hm:
            if h.hspHitFrom and h.hspHitTo and str(h.hspExpect):
                gdPlot.plotHit(int(h.hspHitTo*rpt), int(h.hspHitFrom*rpt), header, _blastScoreVsColor(h.hspExpect), head=head)
                head = False
                nbhit +=1
            if expend:
                gdPlot._nbligneP()
        gdPlot._nbligneP()
    gdPlot._nbligneP()
    gdPlot.plotSeq( seqlen=p_all['dbSeq'][1], start=0, stop=sizeX, header = p_all['dbSeq'][0].accession, color = 'red', up = False )
    gdPlot.legend()
    if typep == 'png' and nbhit > 0:
        picturefh = open( pictureFileName, "w")
        gdPlot.picture.writePng(picturefh)
        picturefh.close()
    
################################################
#
#   HSP analysis tools
#
################################################

def extractDBSeqMaxRepresented( vprotRecord ):
    """ Find species (seqRef)"""
    # vprotRecord = vprot['record'] = [{'blastrecord':blastRecord,'hit': [(blastHitRecord, dbRecord)] }]
    dbAnalyse = {}
    for vprd in vprotRecord:
        # vprd =  [{'blastrecord':blastRecord,'hit': [(blastHitRecord, dbRecord), ...] }]
        for blastHitRecord, dbRecord in vprd['hit']:
            if dbAnalyse.has_key( dbRecord.accession ):
                dbAnalyse[dbRecord.accession]['nb'] +=1
                dbAnalyse[dbRecord.accession]['hits'].append( (blastHitRecord, dbRecord, vprd['blastrecord']) )
            else:
                dbAnalyse[dbRecord.accession] = {'nb' : 1, 'hits' : [ (blastHitRecord, dbRecord, vprd['blastrecord']) ] }
    
    maxi = 0
    record=[]
    for v in dbAnalyse.values():
        if v['nb'] > maxi:
            maxi = v['nb']
            record = [ v['hits'] ]
        elif v['nb'] == maxi:
            record.append( v['hits'] )
    
    #record = [ hits ] = [ [ (blastHitRecord, dbRecord,vprd['blastrecord']),... ],... ]
    #                  = [ [ (blastHitRecord, dbRecord, blastRecord),... ],... ]
    return record

def extractBestHSPs( hspS, hspOutMode = 1, res =[], delta = 10 ):
    """ Select hsp related to option"""
    #hspOutMode: 1 - compatible
    #            2 - simple overlap
    #            3 -  
    if hspOutMode == 0: return hspS
    if not hspS:
        return res
    firstHsp = hspS[0]
    compat = True
    #print ';;'
    #printHsp( sys.stdout, firstHsp )
    
    for hsp in hspS[1:]:
        #print '::'
        #printHsp( sys.stdout, hsp )
        if not firstHsp.isCompatible( hsp ):
            if hspOutMode == 1:
                if firstHsp.isBetter( hsp ):
                    hspS.remove( hsp )
                else:
                    try:
                        hspS.remove( firstHsp )
                    except: pass
                    compat = False
                    break
            else:
                dlt =  int(max(firstHsp.hspAlignLen, hsp.hspAlignLen)*(float(delta)/100))
                ### 10% de l'alignement et non des an
                if (firstHsp.isQueryOverlap( hsp, dlt ) and (firstHsp.isDBCompatible(hsp) and firstHsp.dbNotReverse( hsp))) or (hspOutMode == 2 and firstHsp.isQueryCompatible(hsp) and firstHsp.isDBOverlap( hsp, dlt )) or (hspOutMode == 2 and firstHsp.isQueryOverlap( hsp, dlt ) and (firstHsp.isDBOverlap( hsp, dlt ) and firstHsp.dbNotReverse( hsp))) or (hspOutMode == 3 and firstHsp.isQueryCompatible(hsp) and firstHsp.isDBincluded( hsp )):
                    try:
                        hspS.remove( firstHsp )
                    except: pass
                    compat = True
                    break
                else:
                    if firstHsp.isBetter( hsp ): 
                        hspS.remove( hsp )
                    else:
                        try:
                            hspS.remove( firstHsp )
                        except: pass
                        compat = False
                        break
        else:
            # compat tjs True
            try:
                hspS.remove( firstHsp )
            except: pass
            
    if compat:
        res.append( firstHsp )
        try:
            hspS.remove( firstHsp )
        except: pass
    res = extractBestHSPs( hspS, hspOutMode, res )
    return res

def printHsp( fh, hsp ):
    """ Hsp display"""
    if not hsp.hspNum:
        print >>fh, '  %s' % 'No report for high-scoring segment pairs in blast'
    else:
        if hsp.hspAlignLen:
            print >>fh, '  Hsp: %s (%s letters)' % ( hsp.hspNum, hsp.hspAlignLen)
        else:
            print >>fh, '  Hsp: %s' % ( hsp.hspNum )
        print >>fh, '  E-value: %s' % hsp.hspExpect
        if hsp.hspQueryFrom and hsp.hspQueryTo and hsp.hspHitFrom and hsp.hspHitTo:
            print >>fh, '  %s' % hsp.hspQueryFrom, ':', hsp.hspQueryTo
            print >>fh, '  %s' % hsp.hspHitFrom, ':', hsp.hspHitTo
            #print >>fh, '  %s' % hsp.hspQseq[0:20], ':', hsp.hspQseq[-20:]
            #print >>fh, '  %s' % hsp.hspHseq[0:20], ':', hsp.hspHseq[-20:]
            #print >>fh, hsp.hspHseq
            #print >>fh, hsp.hspMidline
            #print >>fh, hsp.hspQseq
        else:
            print >>fh, '  %s' % 'No report fot high-scoring segment pairs in blast'
    #print >>fh, hsp.hspIdentity
    #print >>fh, hsp.hspPositive
    #print >>fh, hsp.hspGap
    #print >>fh, hsp.hspAlignLen
        if hsp.hspQueryFrame and hsp.hspHitFrame:
            print >>fh, ' Frame = %s / %s\n' % (hsp.hspQueryFrame, hsp.hspHitFrame)
        elif hsp.hspQueryFrame:
            print >>fh, ' Frame = %s\n' % hsp.hspQueryFrame
        elif hsp.hspHitFrame:
            print >>fh, ' Frame = %s\n' % hsp.hspHitFrame


def sortHspSByHspHitFrom( hspS ):
    
    hspS.sort(lambda x, y: cmp(x.hspHitFrom, y.hspHitFrom))
    return hspS
    
def splitHspByHitFrame( hspS ): 
    """ split hsps by hitFrame"""
    hs_p = []
    hs_m = []
    for hsp in hspS:
        if hsp.hspHitFrame < 0:
            hs_m.append(hsp)
        else:
            hs_p.append(hsp)
    return hs_p, hs_m


def sortHitByHsphitFrom( hits ):
    """ sort hits (all queries) by first hsphitFrom position (which are sort by query)"""
    # hits = [ [ (blastHitRecord, dbRecord, blastRecord),... ],... ]
    hs_p = [] #hitFrame +, 
    hs_m = [] #hitFrame -
    
    #hitFrame +, 
    hits.sort(lambda x, y: cmp(x[0].hspS[0].hspHitFrom, y[0].hspS[0].hspHitFrom))
    return hits

################################################
#
#   HSP display
#
################################################
def _hspseq2fasta( queryDef, accession, hsp, sequence='', QR=False, HR=False, colwidth=80 ):
    """ format hspQuery seq in fasta format. """
    
    if HR:
        stHR='R'
    else:
        stHR=''
    if not QR:
        str = '>%s_#%s_#Q%s:%s_%sH%s:%s\n' % (queryDef, accession, hsp.hspQueryFrom, hsp.hspQueryTo, stHR, hsp.hspHitFrom,hsp.hspHitTo)
    else:
        str = '>%s_#%s_#RQ%s:%s_%sH%s:%s\n' % (queryDef, accession, hsp.hspQueryFrom, hsp.hspQueryTo, stHR, hsp.hspHitFrom,hsp.hspHitTo)
    i = 0
    
    while i < len(sequence):
        str += sequence[i:i+colwidth]+'\n'
        i = i + colwidth
    str += sequence[i:]
    return str[:-1]

def queryHsp2FastaF( qrfh, dbRecord, p_all, format=0 ):
    """ print hspQuery sequence in fasta format in file"""
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    iterator = extractfasta.FastaIterator( qrfh )
    fastarecord = iterator.next( format=format )
    while fastarecord:
        fastaSeq = ''
        if not fastarecord.sequence:
            # duplicate query
            continue
        try:
            ind = [blrd.queryDef for blrd, hspSs_hp, hspSs_hm in p_all['hit']].index(fastarecord.id)
            blastRecord, hspSs_hp, hspSs_hm=p_all['hit'][ind]
            if len(fastarecord.sequence) != blastRecord.queryLength:
                # duplicate query pb or query not same blast query
                p_all['hit'].pop(ind)
                continue
            hspSs = hspSs_hp + hspSs_hm
            for hsp in hspSs:
                if hsp.hspHitFrame>=0:
                    HR= False
                else:
                    HR= True
                if (hsp.hspQueryFrom and hsp.hspQueryTo ) and hsp.hspQueryFrame>=0:
                    fastaSeq = fastarecord.sequence[hsp.hspQueryFrom-1: hsp.hspQueryTo]
                    if fastaSeq:
                        #duplicate query with different lenth. len(sequence) < hsp.hspQueryFrom, hsp.hspQueryTo
                        qrHspExtractfh = open( 'qrHSPs@'+dbRecord.accession+'.fasta','a')
                        print >>qrHspExtractfh, _hspseq2fasta(blastRecord.queryDef, dbRecord.accession, hsp, fastaSeq, QR=False, HR=HR)
                        qrHspExtractfh.close()
                    else:
                        #remove (blastRecord, hspSs_hp, hspSs_hm) from hits
                        p_all['hit'].pop(ind)
                elif (hsp.hspQueryFrom and hsp.hspQueryTo ):
                    fastaSeq = fastarecord.sequence[hsp.hspQueryTo-1: hsp.hspQueryFrom]
                    if fastaSeq:
                        #duplicate query with different lenth. len(sequence) < hsp.hspQueryFrom, hsp.hspQueryTo
                        qrHspExtractfh = open( 'qrHSPs@'+dbRecord.accession+'.fasta','a')
                        print >>qrHspExtractfh, _hspseq2fasta(blastRecord.queryDef, dbRecord.accession, hsp, fastaSeq, QR=True, HR=HR)
                        qrHspExtractfh.close()
                    else:
                        #remove (blastRecord, hspSs_hp, hspSs_hm) from hits
                        p_all['hit'].pop(ind)
        except:
            pass
        fastarecord = iterator.next(format=format)

def _splitHspS4aliModeByHsphit( pallHits ):
    """ sort all hsp by hspHitFrom: --> 2 lists: Frame pos and Frame neg"""
    #pallHits = [(blastRecord, hspSs_hp, hspSs_hm), ...] ---> hs_p = [(blastRecord, hsp_hp), (blastRecord, hsp_hp) ...]
    
    hs_p = [] #hitFrame +, 
    hs_m = [] #hitFrame -
    for blastRecord, hspSs_hp, hspSs_hm in p_all['hit']:
        for hsp_p in hspSs_hp:
            hs_p.append( (blastRecord,hsp_p) )
        for hsp_m in hspSs_hm:
            hs_m.append( (blastRecord,hsp_m) )
    hs_p.sort(lambda x, y: cmp(x[1].hspHitFrom, y[1].hspHitFrom)) # (1:5), (2:7), (8:10)
    hs_m.sort(lambda x, y: cmp(x[1].hspHitTo, y[1].hspHitTo)) # (5:1), (7:2), (10:8)
    return hs_p, hs_m

def _alignMode_1( hs_hp, hs_hm, dbsequence, colwidth, hj=1): ## WARNING: only positive frame are 
    """ alignment of hsps: query VS seqref: mode 1: hspblastMerge"""
    #hits.sort(lambda x, y: cmp(x[1][0].hspS[0].hspHitFrom, y[0][0].hspS[0].hspHitFrom))
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    stqr = ''
    stdb = ''
    stmid =''
    start = 0
    
    for blastRecord, hsp in hs_hp:
        #Frame +: map queries on dbref
        #print start, ':', hsp.hspHitFrom, hsp.hspHitTo
        #print 'Query: %s' % (blastRecord.queryDef)
        #printHsp( sys.stdout, hsp )
        if start <= hsp.hspHitFrom/hj:
            stdb += dbsequence[start:(hsp.hspHitFrom-1)/hj] + hsp.hspHseq
            stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + hsp.hspMidline
            stqr += ((hsp.hspHitFrom  -1)/hj - start)*'.' + hsp.hspQseq
            start = hsp.hspHitTo/hj
        elif hsp.hspHitTo/hj > start:
            deb, toto = 0, hsp.hspHitFrom/hj
            for i in range(len(hsp.hspHseq)):
                if hsp.hspHseq[i] != '-': 
                    toto += 1
                deb += 1
                if toto == start:
                    break
            if hj == 1:
                deb +=1
            stdb +=  hsp.hspHseq[deb:]
            stmid += hsp.hspMidline[deb:]
            stqr += hsp.hspQseq[deb:]
            start = hsp.hspHitTo/hj
        #print '--'
    for blastRecord, hsp in hs_hm: # hspHit with no negative Frame like now. TBlastX !!!!
        print 'ici'
    stdb += dbsequence[start:].lower()
    stmid += (len(dbsequence) - start)*' ' 
    stqr += (len(dbsequence) - start)*'.' 
    
    other = [] # for align_mode2
    return stdb, stmid, stqr, other



def _alignMode_4( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format=0): ## WARNING: only positive frame are 
    """ alignment of part of query VS seqref: not blast aln"""
    #hits.sort(lambda x, y: cmp(x[1][0].hspS[0].hspHitFrom, y[0][0].hspS[0].hspHitFrom))
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    stqr = ''
    stdb = ''
    stmid =''
    start = 0
    
    for blastRecord, hsp in hs_hp:
        #print '-- ', blastRecord.queryDef
        #Frame +: map queries on dbref
        #print start, ':', hsp.hspHitFrom, hsp.hspHitTo
        #print 'Query: %s' % (blastRecord.queryDef)
        #printHsp( sys.stdout, hsp )
        
        #pos = queryHspseqfh.tell()
        iterator = extractfasta.FastaIterator( queryHspseqfh )
        fastarecord = iterator.next( format=format )
        queryHspSeq = ''
        while fastarecord:
            fld= fastarecord.id.split('_#')
            qry, hit = fld[2].split('_')
            if blastRecord.queryDef == fld[0]:
                fld1=  hit.split('H')
                if fld1[0] == '' and fld1[1] =='%s:%s' % (hsp.hspHitFrom,hsp.hspHitTo):
                    #print int( qry.split('Q')[1].split(':')[1]) - int( qry.split('Q')[1].split(':')[0]),  len(fastarecord.sequence)
                    queryHspSeq = fastarecord.sequence
            fastarecord = iterator.next( format=format )
        queryHspseqfh.seek(0)
        
        if start <= hsp.hspHitFrom/hj:
            #print 'Frame' , hsp.hspQueryFrame, queryHspSeq
            #print '1-', len(dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo].upper()), hsp.hspQueryTo - hsp.hspQueryFrom , len(queryHspSeq)
            stdb += dbsequence[start:(hsp.hspHitFrom-1)/hj] + dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo].upper()
            #stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + hsp.hspMidline
            stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + len(dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo])*'+'
            if hsp.hspQueryFrame < 0:
                queryHspSeq = reverseComp(queryHspSeq)
            stqr += ((hsp.hspHitFrom  -1)/hj - start)*'.' + queryHspSeq
            start = hsp.hspHitTo/hj
        elif hsp.hspHitTo/hj > start:
            deb = start - hsp.hspHitFrom/hj +1
            #print '2-', deb, len(dbsequence[start:hsp.hspHitTo].upper()), len(queryHspSeq[deb:]), hsp.hspHitTo - start
            stdb +=  dbsequence[start:hsp.hspHitTo].upper()
            stmid += len(dbsequence[start:hsp.hspHitTo])*'+'
            if hsp.hspQueryFrame < 0:
                queryHspSeq = reverseComp(queryHspSeq)
            stqr += queryHspSeq[deb:]
            start = hsp.hspHitTo/hj
        #print '--'
    for blastRecord, hsp in hs_hm: # hspHit with no negative Frame like now. TBlastX !!!!
        pass
    stdb += dbsequence[start:].lower()
    stmid += (len(dbsequence) - start)*' ' 
    stqr += (len(dbsequence) - start)*'.' 
    
    other = [] # for align_mode2
    return stdb, stmid, stqr, other

def _alignMode_5( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format=0): ## WARNING: only positive frame are 
    """ alignment of part of query VS seqref: not blast aln"""
    #hits.sort(lambda x, y: cmp(x[1][0].hspS[0].hspHitFrom, y[0][0].hspS[0].hspHitFrom))
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    stqr = ''
    stdb = ''
    stmid =''
    start = 0
    other = []
    for blastRecord, hsp in hs_hp:
        #print '-- ', blastRecord.queryDef
        #Frame +: map queries on dbref
        #print start, ':', hsp.hspHitFrom, hsp.hspHitTo
        #print 'Query: %s' % (blastRecord.queryDef)
        #printHsp( sys.stdout, hsp )
        
        #pos = queryHspseqfh.tell()
        iterator = extractfasta.FastaIterator( queryHspseqfh )
        fastarecord = iterator.next( format=format )
        queryHspSeq = ''
        while fastarecord:
            fld= fastarecord.id.split('_#')
            qry, hit = fld[2].split('_')
            if blastRecord.queryDef == fld[0]:
                fld1=  hit.split('H')
                if fld1[0] == '' and fld1[1] =='%s:%s' % (hsp.hspHitFrom,hsp.hspHitTo):
                    #print int( qry.split('Q')[1].split(':')[1]) - int( qry.split('Q')[1].split(':')[0]),  len(fastarecord.sequence)
                    queryHspSeq = fastarecord.sequence
            fastarecord = iterator.next( format=format )
        queryHspseqfh.seek(0)
        
        if start <= hsp.hspHitFrom/hj:
            #print 'Frame' , hsp.hspQueryFrame, queryHspSeq
            #print '1-', len(dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo].upper()), hsp.hspQueryTo - hsp.hspQueryFrom , len(queryHspSeq)
            stdb += dbsequence[start:(hsp.hspHitFrom-1)/hj] + dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo].upper()
            #stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + hsp.hspMidline
            stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + len(dbsequence[(hsp.hspHitFrom-1)/hj:hsp.hspHitTo])*'+'
            if hsp.hspQueryFrame < 0:
                queryHspSeq = reverseComp(queryHspSeq)
            stqr += ((hsp.hspHitFrom  -1)/hj - start)*'.' + queryHspSeq
            start = hsp.hspHitTo/hj
        else:
            deb = start - hsp.hspHitFrom/hj +1
            # 'gap insertion' in old alignment if gap exists in new hsp
            lidh = lfind(dbsequence[start:deb], '-')
            lidq = lfind(stdb[:hsp.hspHitFrom/hj], '-')
            down = len(stdb)
            up = (hsp.hspHitFrom+stdb[:hsp.hspHitTo].count('-')-1)/hj
            stdb =  wreplace( 'stdb:', stdb, up, down, winsert(stdb[up:], lidh) )
            stmid= wreplace( 'stmid:', stmid, up, down, winsert(stmid[up:], lidh) )
            stqr = wreplace( 'stqr:', stqr, up, down, winsert(stqr[up:], lidh) )
            k = 0
            while k < len(other):
                #print len(other[k]), start, stop, len(winsert( other[k][start:stop], lidh))
                other[k]  = wreplace( 'other:', other[k] , up, down, winsert( other[k][up:down], lidh) )
                k +=1
            # 'new hsp'
            if hsp.hspQueryFrame < 0:
                queryHspSeq = reverseComp(queryHspSeq)
            if hsp.hspHitTo/hj < start:
                new = (hsp.hspHitFrom/hj + len(lidq) -1/hj)*'.'+ queryHspSeq
                other.append(new)
            else:
                #new = (down - len(lid))*'.'+ hsp.hspQseq
                new = (hsp.hspHitFrom/hj + len(lidq) -1/hj)*'.'+ queryHspSeq
                other.append(new)
            stdb +=  dbsequence[start:hsp.hspHitTo].upper()
            stmid += len(dbsequence[start:hsp.hspHitTo])*'+'
            stqr += queryHspSeq[deb:]
            if hsp.hspHitTo/hj >= start:
                start = hsp.hspHitTo/hj

        #print '--'
    for blastRecord, hsp in hs_hm: # hspHit with no negative Frame like now. TBlastX !!!!
        pass
    stdb += dbsequence[start:].lower()
    stmid += (len(dbsequence) - start)*' ' 
    stqr += (len(dbsequence) - start)*'.' 
    j = 0
    while j < len(other):
        other[j] = other[j] + (len(stdb) -len (other[j]))*'.' 
        j+=1

    return stdb, stmid, stqr, other
       
def _alignMode_2( hs_hp, hs_hm, dbsequence, colwidth, hj=1 ): ## WARNING: only positive frame are 
    """ alignment of hsps VS seqref: mode 2: hspblast multiple display"""
    #hits.sort(lambda x, y: cmp(x[1][0].hspS[0].hspHitFrom, y[0][0].hspS[0].hspHitFrom))
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    stqr = ''
    stdb = ''
    stmid =''
    start = 0
    other= []
   
    for blastRecord, hsp in hs_hp:
        #Frame +: map queries on dbref
        #print start, ':', hsp.hspHitFrom, hsp.hspHitTo
        #print 'Query: %s' % (blastRecord.queryDef)
        #printHsp( sys.stdout, hsp )
        if start <= hsp.hspHitFrom/hj:
            stdb += dbsequence[start:(hsp.hspHitFrom-1)/hj] + hsp.hspHseq
            stmid += ((hsp.hspHitFrom -1)/hj - start)*' ' + hsp.hspMidline
            stqr += ((hsp.hspHitFrom  -1)/hj - start)*'.' + hsp.hspQseq
            start = hsp.hspHitTo/hj
        else:
            deb, toto = 0, hsp.hspHitFrom/hj
            for i in range(len(hsp.hspHseq)):
                if hsp.hspHseq[i] != '-': 
                    toto += 1
                deb += 1
                if toto == start:
                    break
            if hj == 1:
                deb +=1
            # 'gap insertion' in old alignment if gap exists in new hsp
            lidh = lfind(hsp.hspHseq[:deb], '-')
            lidq = lfind(stdb[:hsp.hspHitFrom/hj], '-')
            down = len(stdb)
            up = (hsp.hspHitFrom+stdb[:hsp.hspHitTo].count('-')-1)/hj
            stdb =  wreplace( 'stdb:', stdb, up, down, winsert(stdb[up:], lidh) )
            stmid= wreplace( 'stmid:', stmid, up, down, winsert(stmid[up:], lidh) )
            stqr = wreplace( 'stqr:', stqr, up, down, winsert(stqr[up:], lidh) )
            k = 0
            while k < len(other):
                #print len(other[k]), start, stop, len(winsert( other[k][start:stop], lidh))
                other[k]  = wreplace( 'other:', other[k] , up, down, winsert( other[k][up:down], lidh) )
                k +=1
            # 'new hsp'
            if hsp.hspHitTo/hj < start:
                new = (hsp.hspHitFrom/hj + len(lidq) -1/hj)*'.'+ hsp.hspQseq
                other.append(new)
            else:
                #new = (down - len(lid))*'.'+ hsp.hspQseq
                new = (hsp.hspHitFrom/hj + len(lidq) -1/hj)*'.'+ hsp.hspQseq
                other.append(new)
            stdb +=  hsp.hspHseq[deb:]
            stmid += hsp.hspMidline[deb:]
            stqr += len(hsp.hspQseq[deb:])*'.'
            if hsp.hspHitTo/hj >= start:
                start = hsp.hspHitTo/hj
        #print '--'
    for  blastRecord, hsp in hs_hm: # hspHit with no negative Frame like now. TBlastX !!!!
        pass
    stdb += dbsequence[start:].lower()
    stmid += (len(dbsequence) - start)*' ' 
    stqr += (len(dbsequence) - start)*'.' 
    j = 0
    while j < len(other):
        other[j] = other[j] + (len(stdb) -len (other[j]))*'.' 
        j+=1

    return stdb, stmid, stqr, other


code = {1:{'TTT':'F','TTC':'F','TTA':'L','TTG':'L','TCT':'S','TCC':'S','TCA':'S','TCG':'S',
           'TAT':'Y','TAC':'Y','TAA':'*','TAG':'*','TGT':'C','TGC':'C','TGA':'*','TGG':'W',
           'CTT':'L','CTC':'L','CTA':'L','CTG':'L','CCT':'P','CCC':'P','CCA':'P','CCG':'P',
           'CAT':'H','CAC':'H','CAA':'Q','CAG':'Q','CGT':'R','CGC':'R','CGA':'R','CGG':'R',
            'ATT':'I','ATC':'I','ATA':'I','ATG':'M','ACT':'T','ACC':'T','ACA':'T','ACG':'T',
            'AAT':'N','AAC':'N','AAA':'K','AAG':'K','AGT':'S','AGC':'S','AGA':'R','AGG':'R',
            'GTT':'V','GTC':'V','GTA':'V','GTG':'V','GCT':'A','GCC':'A','GCA':'A','GCG':'A',
            'GAT':'D','GAC':'D','GAA':'E','GAG':'E','GGT':'G','GGC':'G','GGA':'G','GGG':'G'}
            }

def _alignMode_3( hs_hp, hs_hm, dbsequence, colwidth, hj=1 ):
    stdb, stmid, stqr, other = _alignMode_2( hs_hp, hs_hm, dbsequence, colwidth, hj )
    stmid = consensus(stqr, other)
    return stdb, stmid, stqr, other

def _alignMode_6( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format=0):
    stdb, stmid, stqr, other = _alignMode_5( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format )
    stmid = consensus(stqr, other)
    return stdb, stmid, stqr, other

def consMax( l ):
    max = 0
    vu = ['.']
    value = '.'
    for e in l:
        if e in vu:
            pass
        else:
            vu.append(e)
            ctp = l.count( e )
            if max < ctp:
                max = ctp
                value = e
    return value 
            
def consensus(stqr, other):
    cons = ''
    i = 0
    while i< len(stqr):
        cons += consMax([e[i] for e in [ stqr] + other])
        i +=1
    return cons
    
def reverseComp(seq):
    new = ''
    d = {'T':'A', 'A':'T', 'C':'G','G':'C', 'K':'N', }
    for a in seq:
        try:
            new = d[a]+ new
        except:
            new = '*' + new
    return new

def translation( sequence, genetic_code):
    prot = ""
    for i in range(0,len(sequence),3):
        codon = sequence[i:i+3].upper()
        if len(codon)%3 == 0:
            try:
                prot = prot + genetic_code[codon].lower()
            except:
                prot = prot + '.'
        else:
            prot = prot + len(codon)*'+'
    return prot

def lfind( word, car = '-' ):
    "Return indexes in s where caracter is found--> list"
    lid = []
    for i in range( len(word) ):
        if word[i] == car:
            lid.append(i)
    return lid      

def winsert( word, lpos, car = '-'):
    delta = 0
    nw = word
    for pos in lpos:
        nw = nw[:pos+delta] + car + nw[pos+delta:]
        #delta += 1
    return nw
    
def wreplace( tag, word, start, stop, nword ):   
    return word[:start]+nword+ word[stop:]
    
def align( alnfh, p_all,  alignMode=1, colwidth=70, genetic_code=1, queryHspseqfh=None, format=0 ):
    """ alignment of hsps VS seqref """
    #p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0}
    #p_all['hit']= [(blastRecord, hspSs_hp, hspS_hm) )]
    #hspSs_hp=[hsp]  hspSs ....> sorted by hsp (hitFrame positive)
    #hspSs_hm=[hsp]  hspSs ....> sorted by hsp (hitFrame minus)
    # alignMode
    #   1 ... hsp blast and database sequence ref alignment: hsp merged in pairwise alignment.
    #   2 ... hsp blast and database sequence ref alignment: hsp in multiple alignment.
    #   3 ... hsp blast and database sequence ref alignment: hsp in multiple alignment and consensus        
    #   4 ... part of queries (hsp) and database sequence ref alignment: queries merged in pairwise alignment. 
    #   5 ... part of queries (hsp) and database sequence ref alignment: queries in multiple alignment
    #   6 ... part of queries (hsp) and database sequence ref alignment: queries in multiple alignment and consensus
    #### FAIRE MIEUX
    
    acc = p_all['dbSeq'][0].accession
    db = p_all['dbSeq'][0].database
    qj, hj=1, 1
    dbsequence = doGolden( db, acc, seqOnly=True, format = 'raw'  )
    len_dbseq = len(dbsequence)
    if blastRecord.program in ['TBLASTX', 'TBLASTN' ] and alignMode not in [4,5,6]:
        #Genetic code used for database translation
        dbsequence = translation( dbsequence, code[genetic_code] )
        hj=3
    elif blastRecord.program in ['BLASTX', 'TBLASTX' ]:
        qj = 3
    #########    
    hs_hp,hs_hm  = _splitHspS4aliModeByHsphit(p_all['hit']) # all hsps sort by HitFrom by Frame. 
    tag = 'identity: '
    if alignMode == 1:
        stdb, stmid, stqr, other = _alignMode_1( hs_hp, hs_hm, dbsequence, colwidth, hj )
    elif alignMode == 2:
        stdb, stmid, stqr, other = _alignMode_2( hs_hp, hs_hm, dbsequence, colwidth, hj )
    elif alignMode == 3:
        stdb, stmid, stqr, other = _alignMode_3( hs_hp, hs_hm, dbsequence, colwidth, hj )
        tag='consensus:'
    elif alignMode == 4:
        #    ['TBLASTX', 'TBLASTN' ] ['BLASTX']
        if blastRecord.program in ['BLASTX']:
            print >>sys.stderr, '-a 4 option is not compatible with BLASTX program. DNA query vs Protein database'
            sys.exit()
        stdb, stmid, stqr, other = _alignMode_4( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format )
    elif alignMode == 5:
        #    ['TBLASTX', 'TBLASTN' ] ['BLASTX']
        if blastRecord.program in ['BLASTX']:
            print >>sys.stderr, '-a 5 option is not compatible with BLASTX program. DNA query vs Protein database'
            sys.exit()
        stdb, stmid, stqr, other = _alignMode_5( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format )
    elif alignMode == 6:
        #    ['TBLASTX', 'TBLASTN' ] ['BLASTX']
        if blastRecord.program in ['BLASTX']:
            print >>sys.stderr, '-a 6 option is not compatible with BLASTX program. DNA query vs Protein database'
            sys.exit()
        stdb, stmid, stqr, other = _alignMode_6( hs_hp, hs_hm, dbsequence, colwidth, qj, hj, queryHspseqfh, format )
        tag = 'consensus:'
        
    alnStr ={1: 'hsps blast and database sequence ref alignment: hsp merged in pairwise alignment',
             2: 'hsps blast and database sequence ref alignment: hsp in multiple alignment',
             3: 'hsps blast and database sequence ref alignment: hsp in multiple alignment and consensus',      
             4: 'part of queries (hsp) and database sequence ref alignment: queries merged in pairwise alignment',
             5: 'part of queries (hsp) and database sequence ref alignment: queries in multiple alignment',
             6: 'part of queries (hsp) and database sequence ref alignment: queries in multiple alignment and consensus'}
    print >>alnfh, "ALIGNEMENT: %s sequence (%s) with all selected queries: %s\n" % (p_all['dbSeq'][0].species, p_all['dbSeq'][0].accession, alnStr[alignMode])
        
    i = 0
    hfr = 1
    ngap = 0
    l = len(str(len_dbseq))
    while i < len(stqr) :
        ht = hfr + (colwidth - stdb[i:i+colwidth].count('-'))*hj -1
        if ht > len_dbseq:
            ht = len_dbseq
        #ngap1 = ngap
        #ngap += stdb[i:i+colwidth].count('-')*hj
        #print >>alnfh,  ('%%-8s:  %%-%ss %%s %%s' % l) % ('ref', hfr,  dbsequence[i-ngap1:(i+colwidth-ngap)], ht)
        print >>alnfh,  ('%%-8s:  %%-%ss %%s %%s' % l) % (p_all['dbSeq'][0].accession[0:8], hfr, stdb[i:i+colwidth], ht)
        hfr = ht+1
        print >>alnfh,  ('%%s %%-%ss %%s %%s' % l) % (tag,' ',  stmid[i:i+colwidth], ' ')
        if tag == 'consensus:':
           print >>alnfh,'' 
        print >>alnfh,  ('Queries:   %%-%ss %%s %%s' % l) % (' ',  stqr[i:i+colwidth], ' ')
        for stqn in other:
            if stqn[i:i+colwidth] != len(stqn[i:i+colwidth])*'.':
            #if 1:
                print >>alnfh,  ('Other:     %%-%ss %%s %%s' % l) % (' ',  stqn[i:i+colwidth], ' ')
        print >>alnfh, ''
        i = i + colwidth
    
    print >>alnfh, 60*"="

    
    
##############################################################################
#
#            MAIN
#
##############################################################################


def usage():
    print """
usage: blast2genoclass [options] -i <blast(s) output file>

Generale options:
   -h  ... Print this message and exit.
   -i  ... Blast(s) output file. One or more blast in one file.

Definition:
    Query Sequence ... Protein or DNA sequence(s) witch are used to made blast(s)
    Query Name     ... Name of sequence witch are used to made blast
    Query File     ... File containing all Query Sequence(s)
    
Description filter:   
   -M/F      ... Filter the one-line description of Blast program with 
               M ... the best hit description.
               F ... the most frequent description.
   -x <int>  ... Number of hits to be concidered per blast (default: 10, all hits: 0 )
   
   -p  <str> ... Filter the one-line description of Blast program with user name. Warning: match exact name.
                   (replace space by _ in name, Envelope_glycoprotein instead of Envelope glycoprotein) 
   
Taxonomic hierarchy filter (mandatory):
   -n <val>  ...  Filter Blast database sequences hits with: 
        
Output:
   -b ... Blast output file matching "Description filter option" are extract from input "blast output 
            file" and reformat in new blast file with ".blast" suffix.
   -q ... Query name(s) matching "Description filter option" are save in file with ".qry" suffix. 
   -v ... Results matching "Description filter option are detailed for all blast in file ("res4individualBlast.txt")
   -V ... Results for database sequence(s) matching "Description filter option" with higher representation
                 in input "blast(s) output file" are save in file ("res4allBlast")
   -m <int> ... Hsp(s) selection
            0 ... All hits displayed
            1 ... Only compatible hits are display in results (default)
            2 ... Simple overlaps are possible 
            3 ... Global overlaps on database sequence(s) are possible
   
   -Q ... Extract Hsp(s) fragment from Query sequence(s) ("HSPs.fasta")
   -f <file> ... Query(s) file
   
   -s ... Database sequence(s) letters (amino or nucleic acids) matching "Description filter option" with higher representation
            in input "blast output file" are save in fata file with "dbfasta" sufix.
   -g ... Picture of hsps
   -a ... Alignment
       1 ... hsps blast and database sequence ref alignment: hsp merged in pairwise alignment.
       2 ... hsps blast and database sequence ref alignment: hsp in multiple alignment.
       3 ... hsps blast and database sequence ref alignment: hsp in multiple alignment and consensus        
       4 ... part of queries (hsp) and database sequence ref alignment: queries merged in pairwise alignment. 
       5 ... part of queries (hsp) and database sequence ref alignment: queries in multiple alignment
       6 ... part of queries (hsp) and database sequence ref alignment: queries in multiple alignment and consensus
Only pairwise and XML Blast output are supported (BLAST 2.2.20 ):

descriptions:

   blast2genoclass filter the one-line description of Blast program.

requirements:

   blast2genoclass use Golden program a Databank flat files entry retriever program wrote by Nicolas Joly (njoly@pasteur.fr) at Institut Pasteur.
"""


if __name__=='__main__':
    from bsddb3 import db
    

    # tmp path
    try:
        TMP_PATH = os.environ[ 'TMPPATH' ]
    except:
        TMP_PATH = "/tmp"

    # ===== System Requirements: golden
    #process = Popen( 'golden', shell=True, stdout=PIPE , stderr=PIPE )
    #err= ''
    #line = process.stderr.readline()
    #while line:
    #    err = err + line
    #   line = process.stdout.readline()
    #if err:
    #    print >>sys.stderr, Blast2GenoClassError('golden not found. It is required.')
    #    sys.exit()
    

    # ===== Command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hn:MFi:p:bqvVsm:gQf:a:x:",["help",] )
    except getopt.GetoptError:
        usage()
        sys.exit( 0 )

    vdefTaxoName = None
    MSP, mostFrequent = False, False
    Emin = 10000000
    fhout= sys.stdout
    hspOutMode, alignMode = '1', '0'
    
    blastoutput, queryoutput, verboseout, verboseDbSeqOut, seqRefOut  = False, False, False, False, False
    qrHspExtract = False
    blastf, queryf, vdefProtName =  None, None, ''
    picture = False
    hitNumber = 10
    for o, v in opts: #( opt, value )
        if o in ( "-h","--help" ):
            usage()
            sys.exit( 0 )
        
        elif o in ( "-M" , "--MSP" ):
            MSP = True
        elif o in ( "-F" , "--MFrequent" ):
            mostFrequent = True
        elif o in ( "-x", "--hitNum" ):
            try:
                hitNumber = int(v)
            except:
                usage()
                sys.exit( 0 )
        elif o in ( "-i" , "--blast" ):
            blastf = v
        elif o in ( "-n" , "--taxoName" ):
            vdefTaxoName = v.replace('_',' ')
        elif o in ( "-p" , "--protName" ):
            vdefProtName = v.replace('_',' ')
        elif o in ( "-b" , "--blastout" ):
            blastoutput = True
        elif o in ( "-q" , "--qryout" ):
            queryoutput = True
        elif o in ( "-v" , "--verbose" ):
            verboseout = True
        elif o in ( "-V" , "--verboseseq" ):
            verboseDbSeqOut = True
        elif o in ("-s", "--dbseq"):
            seqRefOut = True
        elif o in ("-m", "--hspmode"):
            hspOutMode = v
        elif o in ( "-g" , "--graphic" ):
            picture = True
        elif o in ( "-a" , "--align" ):
            alignMode = v
        elif o in ( "-Q" , "--qrHspExt" ):
            qrHspExtract = True
        elif o in ( "-f" , "--queryFile" ):
            queryf = v
        else:
            usage()
            sys.exit( 0 )
    
#    if args:
#        blastname = args[0]
#    else:
#        usage()
#        sys.exit( 0 )

    # === hit filter type
    
    if (MSP and vdefProtName) or (mostFrequent and vdefProtName) or (MSP and mostFrequent):
        usage()
        sys.exit( 0 )

    # === mandatory files

    if not blastf:
        usage()
        sys.exit( 0 )

    # === taxonomic rank filter type

    if  not  vdefTaxoName:
        usage()
        sys.exit( 0 )
    
    # === mode value
    if hspOutMode not in ['0', '1', '2', '3']:
        usage()
        sys.exit( 0 )
    else:
        hspOutMode = int( hspOutMode )
    
    if alignMode not in ['0', '1', '2', '3', '4', '5', '6']:
        usage()
        sys.exit( 0 )
    elif alignMode in ['4', '5','6']:
        if not queryf:
            print "Query(s) File is mandatory with -a 4/5/6 options"
            usage()
            sys.exit( 0 )
        else:
            qrHspExtract = True
            alignMode = int( alignMode )
        
    else:
        alignMode = int( alignMode )
    
    # query extraction with hsp informations
    if (qrHspExtract and not queryf):
        print "Query(s) File is mandatory with -Q options"
        usage()
        sys.exit( 0 )
    
    
    # === file name
    
    if os.path.exists( 'res4individualBlast.txt' ):
        os.unlink( 'res4individualBlast.txt' )
    verboseoutf = "res4individualBlast.txt"
    
    if os.path.exists( 'res4allBlast.txt' ):
        os.unlink( 'res4allBlast.txt' )
    verboseDbSeqOutf = "res4allBlast.txt"
    
    if os.path.exists( 'noHitinBlast.qry' ): #  Blast output: ***** No hits found ******
        os.unlink( 'noHitinBlast.qry' )
    nohitf = "noHitinBlast.qry"
    
    # ===== Blast parsing
    try:
        fhin = open( blastf )
    except IOError, err:
        print >>sys.stderr, err
        sys.exit( 0 )

    blastRecordS, format = BlastParser.parser( fhin )
    
    #if format == 'psiblast':
    #    print >>sys.stderr, Blast2GenoClassError( 'psiblast output is not supported for now' )
    #    sys.exit()
    fhin.close()

    ## Check supported database
    if format not in ['m0','m8']:
        print >>sys.stderr, BlastParser.BlastError("Not an accepted blast format" )
        sys.exit()
    
    if format == 'm0' and blastRecordS.hasDatabase():
        supportedDB = ['imgt', 'tr', 'swissprot', 'sp', 'uniprot', 'uniprot_sprot','uniprot_trembl','emb', 'embl', 'embl_new', 'gp', 'gb', 'genbank', 'genpept', 'nr','nrprot']
        if blastRecordS.database not in supportedDB:
            inDb = False
            for i in supportedDB:
                if (i in blastRecordS.databaseAll.lower()):
                    inDb = True
                    break
            if not inDb:
                print >>sys.stderr, Blast2TaxoClassError( '-%s- database is not supported for now' % blastRecordS.database )
                sys.exit()
    elif format == 'm0':
        print >>sys.stderr, BlastParser.BlastError("Not a valid blast format" )
        sys.exit()
    

    ## for each blast report
    nbBlast = 0
    query = {}
    
    # Open Berkeley database and write its contents out
    # Get an instance of BerkeleyDB 
    osVSocBDB = db.DB()
    # Open database
    #       Access method: Hash
    #       set isolation level to "dirty read (read uncommited)"
    
    osVSocBDBfile = TABLE + TAXODB_BDB
    try:
        osVSocBDB.open(osVSocBDBfile, None, db.DB_HASH, db.DB_RDONLY)
    except StandardError, err:
        print >>sys.stderr, Blast2GenoClassError("TaxoDB database error, %s" % err)
        sys.exit() 
    
    #### for all blast in file
    allBlastProt = {}
    allDBRecord ={} # dbRecord container: one parsing for All blast
    bi = 0
    w=0
    # =====> all blast
    for blastRecord in blastRecordS.blastS:
        # +++++++++> one blast
        bi +=1
        allHitOcRank = []
        Emin = 10000000
        MSP_hit = None
        MSP_dbRecord = None
        blastRecord.database = blastRecordS.database
        nbBlast += 1
        j = 0
        
        # +++++++++> all hit for one blast
        ### ANALYSE, STORAGE, OUTPUT RESULTS FOR ONE BLAST
        blastProt = {}
        if hitNumber == 0:
            hitNumberN = len(blastRecord.hitS)
        else:
            hitNumberN = hitNumber
        for blastHitRecord in blastRecord.hitS[:hitNumberN]:
            # ------------> blast's hit (with hspS) analyze
            firstHSP = blastHitRecord.hspS[0]
            # ------------> blast's best hit
            if MSP and firstHSP.hspExpect < Emin:
                MSP_hit = blastHitRecord
                Emin = firstHSP.hspExpect
                # ----> parse oc, os with BerkeleyDB or golden for one hit
                dbRecord, allDBRecord = extractDBrecord( blastHitRecord, allDBRecord )
                
                if not dbRecord: ##### WARNING: golden error not well deal
                    continue
                MSP_dbRecord = dbRecord
            elif not MSP:
                # parse oc, os with BerkeleyDB or golden
                dbRecord, allDbRecord = extractDBrecord( blastHitRecord, allDBRecord )
                
                if not dbRecord: ##### WARNING: golden error not well deal
                    continue
                # ------------> blast's hit: protein/gene name extraction from one comment
                protBL = ''      # one blast's hit: protein/gene name extraction from blast comment
                db_fld1 = dbRecord.classification.split( ';' )
                for f in range( len(db_fld1) ):
                    name, rank = extractRank( db_fld1[f].strip() )
                    if (vdefTaxoName and vdefTaxoName.replace('_', ' ').lower() == name.lower()):
                        protBL = extractProt( blastHitRecord )
                        if 'error' in protBL:
                            print >>sys.stderr, 'NAME PROT ERROR: %s ' % dbRecord.accession
                # ------------> blast's hit: protein/gene name storage
                #if not protBL:
                #    protBL = 'Protein/Gene Name filtering error'
                if (protBL and protBL != 'error'):
                    if blastProt.has_key( protBL ):
                        blastProt[ protBL ]['nb'] +=1 
                        blastProt[ protBL ]['hit'].append((blastHitRecord, dbRecord))
                    else:
                        blastProt[ protBL ]={'nb' : 1 ,'hit' :  [(blastHitRecord, dbRecord)] }
                
        if MSP and MSP_dbRecord:
            protBL = ''
            db_fld1 = MSP_dbRecord.classification.split( ';' )
            for f in range( len(db_fld1) ):
                    name, rank = extractRank( db_fld1[f].strip() )
                    if (vdefTaxoName and vdefTaxoName.replace('_', ' ').lower() == name.lower()):
                        protBL = extractProt( MSP_hit )
                        if 'error' in protBL:
                            print >>sys.stderr, 'NAME PROT ERROR: %s ' % dbRecord.accession
            if (protBL and protBL != 'error'):
                    if blastProt.has_key( protBL ):
                        blastProt[ protBL ]['nb'] +=1 
                        blastProt[ protBL ]['hit'].append((MSP_hit, dbRecord))
                    else:
                        blastProt[ protBL ]={'nb' : 1 ,'hit' :  [(MSP_hit, dbRecord)] }
                  
            if ( MSP_hit):
                protMSP = extractProt( MSP_hit )
                if protMSP and blastProt.has_key( protMSP ):
                    blastProt[ protMSP ]['MSP'] = 1
        
        # +++++++++> one blast: best prot/gene name for all hits
        bestProtHits = []
        bestProtName = ''
        if len( blastRecord.hitS) > 0: # Warning: Not hit found
            if verboseout:
                verboseoutfh = open( verboseoutf, 'a' )
            # analyse       
            maxi = 0
            if mostFrequent: # extract the most frequent prot/gene name in all blast's comment
                nm = ''
                for k,v in blastProt.items():
                    if v['nb'] > maxi:
                        maxi = v['nb']
                        bestProtName = k
                        bestProtHits = v['hit']
                        # bestProtHits = [(blastHitRecord, dbRecord)]
                if verboseout:
                    perHit = float(len(bestProtHits))*100/len( blastRecord.hitS )
                    verboseOutFile( verboseoutfh, blastRecord, perHit, bestProtName, bestProtHits, hspOutMode )
            elif MSP: # extract the MSP prot/gene name in blast
                if blastProt.has_key( protMSP ):
                    bestProtHits = blastProt[protMSP]['hit']
                    # bestProtHits = [(blastHitRecord, dbRecord)]
                    bestProtName = protMSP
                if verboseout:
                    perHit = float(len(bestProtHits))*100/len( blastRecord.hitS)
                    verboseOutFile( verboseoutfh, blastRecord, perHit, bestProtName, bestProtHits, hspOutMode )
            elif vdefProtName: # extract only user's prot/gene name
                bestProtName = vdefProtName.replace('_', ' ')
                if blastProt.has_key( bestProtName ):
                    bestProtHits = blastProt[ bestProtName ]['hit']
                    # bestProtHits = [(blastHitRecord, dbRecord)]
                    if verboseout:
                        perHit = float(len(bestProtHits))*100/len( blastRecord.hitS)
                        verboseOutFile( verboseoutfh, blastRecord, perHit, bestProtName, bestProtHits, hspOutMode )
            else:
                if verboseout:
                    print >>verboseoutfh, '\n%s:' % blastRecord.queryDef
                for k,v in blastProt.items():
                    bestProtName = k
                    bestProtHits = v['hit']
                    # bestProtHits = [(blastHitRecord, dbRecord)]
                    if verboseout:
                        perHit = float(len(v['hit']))*100/len( blastRecord.hitS)
                        verboseOutFile( verboseoutfh, blastRecord, perHit, bestProtName, bestProtHits, hspOutMode, all=True )
            
            # +++++++++> one blast: storage of bestProtName for future analyse of all blasts
            if bestProtHits and allBlastProt.has_key( bestProtName ):
                allBlastProt[bestProtName]['nb'] += 1
                allBlastProt[bestProtName]['record'].append( {'blastrecord':blastRecord,'hit': bestProtHits } )
            elif bestProtHits:
                allBlastProt[bestProtName] = {'nb':1, 'record': [{'blastrecord':blastRecord,'hit': bestProtHits }] }
            else:
                if allBlastProt.has_key( 'Description filter: No result' ):
                    allBlastProt['Description filter: No result']['nb'] += 1
                    allBlastProt['Description filter: No result']['record'].append( {'blastrecord':blastRecord,'hit': bestProtHits } )
                else:
                    allBlastProt['Description filter: No result']={'nb':1, 'record': [{'blastrecord':blastRecord,'hit': bestProtHits }] }
            
            if verboseout:
                verboseoutfh.close()
        else: # Warning: Not hit found
            if allBlastProt.has_key( 'Blast input file: No hits found' ):
                allBlastProt['Blast input file: No hits found']['nb'] += 1
            else:
                allBlastProt['Blast input file: No hits found']= {'nb': 1, 'record':{} }
            fhoutnoHit = open( nohitf , 'a') #   Blast output: ***** No hits found ******
            print >>fhoutnoHit, blastRecord.queryDef
            
    
    # =====> all blast
    
    ### ANALYSE, OUTPUT (SAMARY, VERBOSE, PICTURE) RESULTS FOR ALL BLAST
    print >>sys.stdout, 'All blasts analyses\n-----------------'
    print >>sys.stdout, 'Percent(%)\tQuery nb\tSeq. description\tMost frequent sequence(s) in blast output'
    for prot, vprot in allBlastProt.items():
        # prot = protInfo
        # vprot = {'nb':1, 'record': [{'blastrecord':blastRecord,'hit': [(blastHitRecord, dbRecord)] }] }
        bestDbSeqhitS = extractDBSeqMaxRepresented( vprot['record'] )
        
        # bestDbSeqhitS =  [ [ (blastHitRecord, dbRecord, blastRecord),... ],... ]
        # liste de hits par blast (qry diff)  pour chaque acc max, 
        listOfBestAcc = [ht[0][1].accession for ht in bestDbSeqhitS]
        if listOfBestAcc:
            print >>sys.stdout, "%-8.2f\t%-8s\t%-20s\t%s" % ( float(vprot['nb'])*100/nbBlast, vprot['nb'], prot, (listOfBestAcc,str(listOfBestAcc[0:5])[:-1]+'...]') [len(listOfBestAcc)>5] )
        else:
            print >>sys.stdout, "%-8.2f\t%-8s\t%-20s" % ( float(vprot['nb'])*100/nbBlast, vprot['nb'], prot )
        outPutFile( prot, vprot, bestDbSeqhitS, blastoutput, format, queryoutput, seqRefOut )
        
        if (verboseDbSeqOut or picture or qrHspExtract or alignMode) and bestDbSeqhitS:
            if verboseDbSeqOut:
                verboseDbSeqOutfh = open( verboseDbSeqOutf,'a')
            
            for bestDbSeqhit in bestDbSeqhitS: ## for each seqRefhit (best acc)
                # bestDbSeqhit = [ (blastHitRecord, dbRecord, blastRecord),... ]
                # for one seqRef, all hits by blast
                dbRecord = bestDbSeqhit[0][1]
                hitLength = bestDbSeqhit[0][0].hitLength #blastHitRecord.hitLength
                if verboseDbSeqOut:
                    print >>verboseDbSeqOutfh, "%s : %s (%s letters): %s " % ( dbRecord.species, dbRecord.accession, hitLength , prot)
                    print >>verboseDbSeqOutfh, "Number of matching query: %s\n" % len (bestDbSeqhit)
                if (picture or alignMode or qrHspExtract) and hitLength:
                    fi = dbRecord.species.replace(' ' ,'_')
                    fi = fi.replace('/' ,'_').replace('(' ,'_').replace(')' ,'_').replace('*', '_').replace('?', '_').replace(':', '_')
                    if picture:
                        pictureFileName = fi+'@'+dbRecord.accession+'.png'
                        
                    if alignMode:
                        #alnfh = open( fi+'@'+dbRecord.accession+'.aln', "w")
                        alnfh = open( fi+'.aln', "a")
                    p_all = {'dbSeq': (dbRecord,hitLength), 'hit':[], 'n_hsp': 0, 'n_qry':0}
                
                ## lourd, tres lourd
                

                # by seqRef, all hits are "NOT SORTED"
                
                # 1: sort hspS by blastHitRecord: ie by blastRecord
                for blastHitRecord, dbRecord, blastRecord in bestDbSeqhit:
                    #bestDbSeqhit = [ (blastHitRecord, dbRecord, vprd['blastrecord']),... ]
                    #             = [ (blastHitRecord, dbRecord, blastRecord),... ]
                    #sort by hspHitFrom
                    blastHitRecord.sortByHspHitFrom() # blastHitRecord.hspS = blastHitRecord.hspSminus + blastHitRecord.hspSplus
                    
                # 2: sort all by blastRecord.hspS[0] 
                ht_sort = sortHitByHsphitFrom( bestDbSeqhit ) # for the display
                for blastHitRecord, dbRecord, blastRecord in ht_sort:
                    hspS_hp=extractBestHSPs( blastHitRecord.hspSplus, hspOutMode, [] )
                    hspS_hm=extractBestHSPs( blastHitRecord.hspSminus, hspOutMode, [] )
                    #hspS_hps = sortHspSByHspHitFrom(hspS_hp)
                    #hspS_hms = sortHspSByHspHitFrom(hspS_hm)
                    hspS = hspS_hp + hspS_hm
                    hspSs = sortHspSByHspHitFrom(hspS)
                    if verboseDbSeqOut:
                        verboseOutFileBestAcc( verboseDbSeqOutfh, blastRecord, hspSs )
                                         
                    if (picture or alignMode or qrHspExtract) and hitLength:
                        ####PB: hspSs trier par blastRecord mais pas par dbseq
                        p_all['hit'].append( (blastRecord, hspS_hp ,hspS_hm) )
                        p_all['n_hsp']+= len(hspSs)
                        p_all['n_qry']+= 1
                if qrHspExtract:
                    try:
                        # reparse a chaque acc
                        qrfh = open( queryf )
                        #qrHspExtractfh = open( 'qrHSPs@'+dbRecord.accession+'.fasta','a')
                        queryHsp2FastaF( qrfh, dbRecord, p_all, format=0 )
                        qrfh.close()
                        #qrHspExtractfh.close()
                    except IOError, err:
                        print >>sys.stderr, err
                if verboseDbSeqOut:
                    print >>verboseDbSeqOutfh, '=' *80
                if picture and hitLength:
                    plot( pictureFileName, p_all, sizeX = 700, typep='png', expend = False )
                if alignMode and hitLength:
                    qryHspseqfh = None
                    if alignMode in [4,5,6]:
                        qryHspseqfh = open( 'qrHSPs@'+dbRecord.accession+'.fasta','r')
                    align( alnfh, p_all, alignMode=alignMode, colwidth=70, genetic_code=1, queryHspseqfh=qryHspseqfh, format=0 )
                    if alignMode in [4,5,6]:
                        qryHspseqfh.close()
            if verboseDbSeqOut:
                verboseDbSeqOutfh.close()
            
    if allBlastProt == {}:
        print >>sys.stdout, "No result (ie: ***** No hits found ****** in Blast)"
    osVSocBDB.close()
