#!/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
#------------------------------------------------

# make sure tmp file cleaning works
tmp_setup_trap

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

# check executable
check_file_exe "$0" "$EXE_GETINPAR" || exit 255

input="$1"
inparr=( $(tokenize ";" $input) )

#-----------------------------------
# fix for run using splits
# check splits file
#splitopt=""
#if is_step_enabled SPLITBRH; then
#    # check split file here even though it is done in step_makeinpar()
#    # they may be run on different machines
#    # NOTE the split file is NEVER compressed
#    [[ -f $SPLIT_FILE ]] || fatal_msg "no split file ($SPLIT_FILE) found!"
#    splitopt="-s $SPLIT_FILE"
#    info_msg "split file to be used: $SPLIT_FILE"
#else
#    info_msg "SPLITBRH not enabled - do not use split file"
#fi
#-----------------------------------

nok=0
nerr=0
# get compression extension
aliext=$(get_cmpext ALIGNMENT)
brhext=$(get_cmpext MAKEBRH)
cmpext=$(get_cmpext MAKEINPAR)

# create tmp files
tmpfile=""
tmpAB=""
tmpBA=""
tmpout=""
tmp_make tmpfile makeinpar
tmp_make tmpAB   uncomp
tmp_make tmpAA   uncomp
tmp_make tmpBB   uncomp
tmp_make tmpout  makeinpar

for args in ${inparr[@]}; do
    argsarr=( $(tokenize "," $args) )
    [[ ${#argsarr[@]} -eq 3 ]] || fatal_msg "run_makeinpar.sh: invalid input ($input), expected comma separated list <idA0,idB0,N;idA1,idB2,N;...> but got <$input>";
    
    rm -f "$tmpfile" && touch "$tmpfile"
    rm -f "$tmpAB"   && touch "$tmpAB"
    rm -f "$tmpBA"   && touch "$tmpAA"
    rm -f "$tmpBA"   && touch "$tmpBB"
    rm -f "$tmpout"  && touch "$tmpout"
    
    # label pair A,B
    A="${argsarr[0]}"
    B="${argsarr[1]}"
    nthreads=${argsarr[2]}

    info_msg "Starting makeinpar job <$A,$B> with N(threads)=$nthreads"

    # get input pair file names
    fABbase="$(get_pwc_file $A $B ${EXT_BRH})"
    fAAbase="$(get_pwc_file $A $A ${EXT_ALIGN})"
    fBBbase="$(get_pwc_file $B $B ${EXT_ALIGN})"

    # get full filenames as expected bny compression
    fAB=$(get_filename "$fABbase" "$brhext") || { m=$(parse_ec_get_filename $?); error_msg "run_makeinpar.sh: $m , file [A,B] $fAB"; continue; }
    fAA=$(get_filename "$fAAbase" "$aliext") || { m=$(parse_ec_get_filename $?); error_msg "run_makeinpar.sh: $m , file [A,A] $fAA"; continue; }
    fBB=$(get_filename "$fBBbase" "$aliext") || { m=$(parse_ec_get_filename $?); error_msg "run_makeinpar.sh: $m , file [B,B] $fBB"; continue; }

    # get inparalog file name (output)
    output="$(get_pwc_file $A $B ${EXT_INPAR})"

    # uncompress brh AB
    useAB="$tmpAB"
    if [[ -n $brhext ]]; then
        uncompress_file2dst "$fAB" "$tmpAB"
        ec=$?
        [[ $ec -eq 0 ]] || fatal_msg "run_makeinpar: unable to uncompress $fAB"
    else
        useAB="$fAB"
    fi

    # uncompress ali AA
    useAA="$tmpAA"
    if [[ -n $aliext ]]; then
        uncompress_file2dst "$fAA" "$tmpAA"
        ec=$?
        [[ $ec -eq 0 ]] || fatal_msg "run_makeinpar: unable to uncompress $fAA"
    else
        useAA="$fAA"
    fi
    
    # uncompress ali BB
    useBB="$tmpBB"
    if [[ -n $aliext ]]; then
        uncompress_file2dst "$fBB" "$tmpBB"
        ec=$?
        [[ $ec -eq 0 ]] || fatal_msg "run_makeinpar: unable to uncompress $fBB"
    else
        useBB="$fBB"
    fi
    
    # options
    # SPLITBRH removed
    #opts="$splitopt --AB $useAB --AA $useAA --BB $useBB -o $MIN_OVERLAP"
    opts="--AB $useAB --AA $useAA --BB $useBB -o $MIN_OVERLAP"

    # run it
    startdate=$(date)
    tA=$(time_msec)
    #"$EXE_GETINPAR" $splitopt --AB "$useAB" --AA "$useAA" --BB "$useBB" -o $MIN_OVERLAP --output "$tmpfile"
    "$EXE_GETINPAR" --AB "$useAB" --AA "$useAA" --BB "$useBB" -o $MIN_OVERLAP --output "$tmpfile"
    err=$?
    [[ $err -eq 0 ]] || fatal_msg "$0 : failed with error = $err"
    dT=$(delta_time $tA)

    # add a header
    add_header_footer $0 "$tmpfile" "$tmpout" "$startdate" $dT "\"$EXE_GETINPAR $opts\""
    if [[ $? -ne 0 ]]; then
        nerr=$((nerr+1))
        continue
    fi

    # compress file
    compress_sync "$tmpout" "$cmpext" "$output" "run_makeinpar.sh"
    ec=$?
    if [[ $ec -eq 0 ]]; then
        nok=$((nok+1))
    else
        nerr=$((nerr+1))
    fi
    
    info_msg "Done makeinpar job <$A,$B>, exit code = $ec"
done
echo

[[ $nerr -eq 0 ]] || { info_msg "Completed $nok succesfully and $nerr with errors"; exit 255; }

