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

# check args
[[ $# -eq 1 ]] || fatal_msg "usage: $0 <label>"

# check required script
cmd="$DIR_ORTHOLOGER_BIN/stats.py"
check_file_exe "$0" "$cmd" || exit 254

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

nok=0
nerr=0
ec=0

######./sbin/stats.py -f Sequences/AFLOR.fs_selected.seqlen  -c 1 -NpgmMS

# loop over set of arguments separated by ';'
for args in ${inparr[@]}; do
    echo
    print_separator
    info_msg "Starting STATS job <$args>"
    print_separator
    echo

    # get input file
    fsel="$DIR_PROJECT_SEQUENCES/${args}.${EXT_FASTA_SELECTED}"
    [[ -f $fsel ]] || { error_msg "missing file $(trim_name $fsel)"; continue; }

    # get sequence length file
    tmp_make tmpseq "seqlen"
    seqlen=$(set_extension "$fsel" "${EXT_FASTA_SEQLEN}")
    $PYTHON3 $DIR_ORTHOLOGER_BIN/get_sequence_lengths.py -f "$fsel" > "$tmpseq"
    ec=$?
    if [[ $? -ne 0 ]]; then
	    error_msg "failed getting sequence lengths for $output -> CHECK FASTA FILE!"
	    nerr=$((nerr+1))
    else
	    # add header/footer - assume dT = 0 secs -> should never be slow... unless I/O pblms...
	    add_header_footer $0 "$tmpseq" "$seqlen" "$(date)" 0 "$DIR_ORTHOLOGER_BIN/get_sequence_lengths.py -f \"$fsel\""
        chmod 644 "$seqlen"
    fi

    # get stats on length file, if ok
    if [[ $nerr -eq 0 ]]; then
	    tmp_make tmpfile fasta_stats
	    startdate=$(date)
	    output=$(set_extension "$fsel" "${EXT_FASTA_STATS}")

	    tA=$(time_msec)

        debug_msg "get average stats"
	    result=($($PYTHON3 $cmd -f "$seqlen" -c 1 -NpgmMS))
	    ec=$?
	    dT=$(delta_time $tA)
        if (( ec == 0 )); then
            # data OK
            nok=$((nok+1))
            if [[ ${#result[@]} -ne 6 ]]; then
                result=( 0 0 0 0 0 0 )
            fi
        else
            # no data available!
            nerr=$((nerr+1))
            error_msg "no data found in seqlen file for taxid $args"
            result=( 0 0 0 0 0 0 )
        fi
	    {
	        echo "#NTOT:${result[0]}"
	        echo "#MINLEN:${result[1]}"
	        echo "#MAXLEN:${result[2]}"
	        echo "#AVELEN:${result[3]}"
	        echo "#MEDLEN:${result[4]}"
	        echo "#TOTLEN:${result[5]}"
	    } > "$tmpfile"

	    if (( ec == 0 )); then
            # add header and footer
            debug_msg "add header"
            add_header_footer $0 "$tmpfile" "$output" "$startdate" $dT "$cmd -c 1 -NpgmMS -f \"$seqlen\""
            if [[ $? -ne 0 ]]; then
                error_msg "failed adding header!"
		        exit 255
            fi
            chmod 644 "$output"
	    fi
    fi
    
    echo
    print_separator
    info_msg "Done STATS job <$args>"
    print_separator
done
echo
[[ $nerr -eq 0 ]] || { error_msg "completed $nok succesfully and $nerr with errors"; exit 255; }
info_msg "completed $nok succesfully"


