#!/usr/bin/python3

# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.
'''
Extract best alignments.
Pipeline usage: OBSOLETE
'''

from __future__ import print_function
#
# This code checks for a given fasta file if the sequences are proteins or nucletides.
#
import operator
import argparse

#-----------------------------------------------------------------
# MAIN
class Data:
    def __init__(self, score, evalue, line):
        # save the negative of the score
        # this is for sorting on ascending values
        self.score=-score
        self.evalue=evalue
        self.line=line

def get_best( keys, maxeval ):
    if len(keys)==0: return None
    if len(keys)>1:
        sorted_keys = sorted( keys, key=operator.attrgetter('evalue','score') )
    else:
        sorted_keys = keys

    # check e-value
    if maxeval>=0 and sorted_keys[0].evalue>maxeval:
        return None;

    return sorted_keys[0]

def find_best( fh, maxeval ):
    lastid=""
    lastkeys=[]
    for line in fh.readlines():
        # make sure line is OK, format is:
        #  id1  id2  score  evalue  percident  start1  end1  start2  end2
        line = line.strip().rstrip('\n')
        if len(line)==0 or line[0]=='#': continue

        # split line
        elems = line.split()
        if not len(elems)==9: continue
        thisid = elems[0]
        if not thisid==lastid:
            # new id, process last set of keys
            if len(lastkeys)>0:
                # sort by evalue and then by score
                best = get_best( lastkeys, maxeval )
                if best is not None:
                    print(best.line)
            # clear lastkeys
            lastkeys=[]
            lastid=thisid

        # add key
        key = Data(float(elems[2]), float(elems[3]), line )
        lastkeys.append(key)

    # capture the last one
    if len(lastkeys)>0:
        best = get_best( lastkeys, maxeval )
        if best is not None:
            print(best.line)

parser = argparse.ArgumentParser(description='find best alignement')

parser.add_argument('-f', '--alignment', dest='filename', help='alignment result file', metavar='FILE')
parser.add_argument('-e', '--maxeval',   dest='maxeval',  help='max e-value, set to <0 if no e-value cut is desired', type=float, default=-1.0)

options = parser.parse_args()

# open fasta file and read data
fh = open(options.filename)

find_best( fh, options.maxeval )

fh.close()
