#!/usr/bin/env bash
#
# 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/>.
#
#--- check if environment is ok -----------------
[[ "${LOADED_COMMON_PIPELINE_SH+1}" == "" ]] && echo "ERROR $0 : main config has not been loaded" 1>&2 && exit 255
#------------------------------------------------

# load profiler
###source $DIR_ORTHOLOGER/bin/profiler.sh
###profile_on
###profile_start_timing "FULL"
###profile_start_timing "PREPROC"

# get args
[[ $# -eq 1 ]] || fatal_msg "Usage: $0 <keyA>,<B>,<nthreads>"

# get and check args
input="$1"
inparr=( $(tokenize ";" $input) )

nok=0
nerr=0

# set to 1 if evalue is to be used for BRH
# it sorts first by score in any case
#DISABLED! Anyway not used... but might be later
###FINDBRH_USE_EVALUE=0

# check findbrh extra options
fuzzyOpts=""
if [[ $MAKEBRH_NALT -gt 1 ]]; then
    fuzzyOpts="--Nalt $MAKEBRH_NALT --fsepmax $MAKEBRH_FSEPMAX"
fi

move_files="echo 'move files'"
tmp_make_dir tmpdir "makebrh"        || exit 255

for args in ${inparr[@]}; do
    
    ###profile_start_timing "PREPROCAB"
    argsarr=( $(tokenize "," $args) )
    [[ ${#argsarr[@]} -eq 3 ]] || fatal_msg "run_makebrh.sh: invalid input ($input), expected comma separated list <idA0,idB0,N;idA1,idB2,N;...> but got <$input>";

    A="${argsarr[0]}"
    B="${argsarr[1]}"
    nthreads=${argsarr[2]}

    info_msg "Starting makebrh job <$A,$B> with N(threads)=$nthreads"
    # source AB,BA files
    fAB="${DIR_PROJECT_PWC}/$A/${A}_${B}.${EXT_ALIGN}"
    fBA=""
    
    # final output
    fBRH="${DIR_PROJECT_PWC}/$A/${A}_${B}.${EXT_BRH}"
    
    # tmp output
    output="$tmpdir/${A}_${B}.${EXT_BRH}"
    
    ###profile_start_timing "PREPROCAB_CHECKFOOTER"
    # check footer
    check_footer "$fAB" || fatal_msg "run_makebrh : missing end tag (#END) in <$fAB>"
    
    # use BA if it exists
    if [[ $ALIGNMENT_MATRIX -eq 0 ]]; then
        fBA="${DIR_PROJECT_PWC}/$B/${B}_${A}.${EXT_ALIGN}"
        check_footer "$fBA" || fatal_msg "run_makebrh : missing end tag (#END) in <$fBA>"
    fi
    ###profile_stop_timing  "PREPROCAB_CHECKFOOTER"
    ###profile_stop_timing  "PREPROCAB"

    # run makebrh, uses the variable nthreads,fAB,fBA,output and fuzzyOpts
    source $DIR_ORTHOLOGER/bin/run_makebrh_base.sh 

    if [[ $MAKEBRH_EC -ne 0 ]]; then
        error_msg "$0 : failed finding BRHs for key pair [$A,$B] with error $MAKEBRH_EC"
        nerr=$((nerr+1))
        continue
    fi
    nok=$((nok+1))
    
    chmod 644 $output
    move_files="$move_files && mv -f $output $fBRH"


    info_msg "Done makebrh job <$A,$B>, exit code = $MAKEBRH_EC"
done

# move all files
###eval $move_files

# move all files
eval $move_files
[[ $?    -eq 0 ]] || { nerr=$((nerr+1)); error_msg "failed moving at least one file"; }
[[ $nerr -eq 0 ]] || { info_msg "Completed $nok succesfully and $nerr with errors"; exit 255; }
###profile_stop_timing "FULL"
###profile_report

