#!/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/>.
#
#
# Run the segmasker tool from blast+ .
#
#--- 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

# --- Check executables ---

# require dustmasker
[ -x "$EXE_DUSTMASKER" ] || fatal_msg "masker plugin : missing dustmasker $EXE_DUSTMASKER"

filter() {
    local fname="$1"
    [ -f "$fname" ] || return 1

    local outfile="$2"

    # check if source is younger than target and if target exists - REMOVE
###    check_if_newer_source "$fname" "$outfile"

    # update only if target does not exist or is younger than source
###    [ $? -eq 0 ] || return 0

    # cp file to temp
    local tmpdata=""
    tmp_make tmpdata "dustmasker_input"
    cp -f "$fname" $tmpdata

    # run segmasker
    local tmpseg=""
    tmp_make tmpseg "dustmasker_output"

    local cmd="$EXE_DUSTMASKER"
    local opts="-in $tmpdata -out $tmpseg -infmt fasta -outfmt fasta $OPTS_DUSTMASKER"

    local startdate=$(date)
    local tA=$(time_msec)
    "$EXE_DUSTMASKER" $opts
    if [ $? -ne 0 ]; then
	    return 5
    fi
    local dT=$(delta_time $tA)

    # segmasker prints all masked out regions in the original character but in lower case
    # we want them to be replaced by a lower case 'x'
    # for all lines not starting with '>' ( /^>/!s/ )
    #   substitute all lower case with x
    # DONT NEED TO DO THIS - filter_masked_fasta.py does it.
###    local tmpseg2=$(mktemp /tmp/seg2)
###    cat $tmpseg | sed '/^>/!s/[a-z]/x/g' > $tmpseg2

    # filter fasta - should have a certain min length of un-masked region and a max fraction of masked
    $PYTHON3 "$DIR_ORTHOLOGER_BIN"/filter_masked_fasta.py -f $tmpseg --maxf 0.95 --minlen $MIN_OVERLAP --type NUCL > "$outfile"

    add_header_footer $0 "$outfile" "$outfile" "$startdate" $dT "\"$cmd $opts\""
    chmod 644 "$outfile"

    return 0
}

[ $# -eq 2 ] || fatal_msg "usage: $0 <fasta> <outfile>"

#nthreads="$1"
fasta="$1"
outfile="$2"
check_file "$0" "$fasta" || exit 255

filter "$fasta" "$outfile" || exit 255


