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

set -u

#--------------------------------
#--- 1. PROCESS ARGUMENTS     ---
#--------------------------------
# get args
[[ $# -eq 4 ]] || fatal_msg "usage: $0 <query file> <DB file> <output> <nthreads>"

query="$1"
dbase="$2"
output="$3"
nthreads=$4

#--------------------------------
#--- 2. CHECK INPUT           ---
#--------------------------------
check_file    "$0" "$query"       || exit 255
check_file    "$0" "$dbase"       || exit 255

#--------------------------------
#--- 3. CHECK REQUIREMENTS    ---
#--------------------------------
# check that formatdb files are there
check_formatdb_files "$query" 0 || exit 255
check_formatdb_files "$dbase" 0 || exit 255

#--------------------------------
#--- 4. SETUP ALIGNMENT CMD     ---
#--------------------------------
outfmt="6 qseqid sseqid score bitscore evalue pident length qlen qstart qend slen sstart send"
options="-evalue $MAX_EVALUE"
###options="$options -max_target_seqs 10"
options="$options -num_alignments $ALIGNMENT_NUMALIGNMENTS $OPTS_BLAST"
options="$options -num_threads $nthreads"

# effective DB size
effdbsz=$(get_effdbsz)
[[ $effdbsz -eq 0 ]] || options="$options -dbsize $effdbsz"

#if [[ "$DATA_TYPE" == "NUCL" ]]; then
#    # Nucleotides
#    BLAST="${EXE_BLASTN}"
#    options="$options -gapopen 3 -gapextend 2 -word_size 11 -strand both -penalty -1 -reward 1"
#else
# Proteins
BLAST="${EXE_BLASTP}"
options="$options -word_size 3 -window_size 50"
#fi

#--------------------------------
#--- 5. RUN ALIGNMENT           ---
#--------------------------------
# run blast
echo "# command: $BLAST $options -query $query -db $dbase -outfmt ${outfmt}"
tmp_make tmpfile blast
startdate=$(date)
tA=$(time_msec)
"$BLAST" $options -query "$query" -db "$dbase" -outfmt "${outfmt}" > $tmpfile
ec=$?
dT=$(delta_time $tA)
if [[ $ec -ne 0 ]]; then
    error_msg "# Failed BLAST+"
    error_msg "# Error  : $ec"
    error_msg "# Time   : $dT"
	error_msg "# Query  : $query"
	error_msg "# DB     : $dbase"
	error_msg "# Output : $(uname -n):$tmpfile"
	tmp_mark_keep "$tmpfile"
    tmp_mark_keep "$query"
    tmp_mark_keep "$dbase"
	exit 255
fi


#--------------------------------
#--- 6. POST-PROCESSING       ---
#--------------------------------
# With blast+ the output format can be user specified and hence no post-reformatting is needed.
# See the variable 'outfmt' above.
# Common output is
#  id1  id2  rawscore bitscore evalue  percident  length seqlen1 start1  end1  seqlen2 start2  end2
#   1    2       3       4        5        6         7      8      9      10      11     12     13

# TARGET FORMAT:
#  id1 id2 score evalue pid start1 end1 start2 end2
#    1   2   3     5     6    9     10    12    13
info_msg "blast: score scale mode = $ALIGNMENT_SCORE_MODE"
trescore=$(time_msec)
{
    print_header "$BLAST $options -query $query -db $dbase -outfmt ${outfmt}" "$startdate"
    common_fmt_header
    #if (( ALIGNMENT_SCORE_MODE == 0 )); then
    #    # S' = 2*S*alnlen/(qlen+tlen)
    #    grep -v "^#" "$tmpfile"    | awk '{ print $1,$2,2.0*$3/($8+$11),$5,$6,$9,$10,$12,$13; }'

    #elif (( ALIGNMENT_SCORE_MODE == 2 )); then
    # S' = 100*S/(query+target lengths) (the scaling is just to make the score a larger number)
    grep -v "^#" "$tmpfile"    | awk '{ print $1,$2,100.0*$3/($8+$11),$5,$6,$9,$10,$12,$13; }'
    
    #elif (( ALIGNMENT_SCORE_MODE == 3 )); then
    #    # S' = S
    #    grep -v "^#" "$tmpfile"    | awk '{ print $1,$2,$3,$5,$6,$9,$10,$12,$13; }'
        
    #elif (( ALIGNMENT_SCORE_MODE == 4 )); then
    #    # use bit score
    #    grep -v "^#" "$tmpfile"    | awk '{ print $1,$2,$4,$5,$6,$9,$10,$12,$13; }'
    #fi
    print_footer "$dT"
} > "$output"

#--------------------------------
#--- 8. CLEANUP               ---
#--------------------------------
chmod 644 "$output"

