#!/bin/bash
 
version="1.4.0"

antismash_run=true
agrobacterium_run=false
macsyfinder_run=true
fuzznuc_run=true
integronfinder_run=true
defensefinder_run=true
tiger_run=true
gapmind_run=true
dbscanswa_run=true
operon_run=false
continue_run=false
bakta_run=true
genbank=false
thread=1
output=$PWD
bakta_args=""
antismash_args=""
#antismash_args="--cb-knownclusters --cc-mibig"
new_input_file=""
tiger_blast_database=""
email=""
circos_run=true

error_exit()
{
	echo "Error: $1"
	exit 1
}

show_help()
{
    echo -e "usage: beav [--input INPUT] [--output OUTPUT_DIRECTORY] [--strain STRAIN] [--bakta_arguments BAKTA_ARGUMENTS] [--tiger_arguments TIGER_ARGUMENTS][--agrobacterium AGROBACTERIUM] [--skip_macsyfinder] [--skip_integronfinder][--skip_defensefinder] [--skip_tiger] [--skip_gapmind][--skip_dcscan-swa] [--skip_antismash] [--help] [--threads THREADS] [--genbank] [--continue]
    BEAV- Bacterial Element Annotation reVamped
    Input/Output:
        --input, -i INPUT.fna
                Input file in fasta nucleotide format (Required)
        --output DIRECTORY
                Output directory (default: current working directory)
        --strain STRAIN
                Strain name (default: input file prefix)
        --bakta_arguments ARGUMENTS
                Additional arguments specific to Bakta
        --antismash_arguments ARGUMENTS
                Additional arguments specific to antiSMASH (Default: \"$antismash_args\")
        --tiger_blast_database DATABASE_PATH
                Path to a reference genome blast database for TIGER2 ICE analysis (Required unless --skip_tiger is used)
        --run_operon_email EMAIL
                Run the Operon-mapper pipeline [remote]. Requires an email address for the operon-mapper webserver job
    Options:
        --agrobacterium
                Agrobacterium specific tools that identify biovar/species group, Ti/Ri plasmid, T-DNA borders, virboxes and traboxes
        --skip_macsyfinder
                Skip detection and annotation of secretion systems
        --skip_integronfinder
                Skip detection and annotation of integrons
        --skip_defensefinder
                Skip detection and annotation of anti-phage defense systems
        --skip_tiger
                Skip detection and annotation of integrative conjugative elements (ICEs)
        --skip_gapmind
                Skip detection of amino acid biosynthesis and carbon metabolism pathways
        --skip_dbscan-swa
                Skip detection and annotation of prophage
        --skip_antismash
                Skip detection and annotation of biosynthetic gene clusters
        --gbk
                Use a GenBank file as input
    General:
        --help, -h
                Show BEAV help message
        --threads, -t
                Number of CPU threads
        --continue
                Continue a previously started run"
}

echo -e "BEAV version $version" | tee -a Beav.log  
echo -e "" | tee -a Beav.log

echo $@ | tee -a Beav.log
echo -e "" | tee -a Beav.log
if [[ -z "${BEAV_DIR}" ]]; then
    echo -e "The BEAV_DIR variable is not set. Either activate the Beav conda environment or set the BEAV_DIR variable." 
    exit
fi
while [ $# -gt 0 ]
do
    case $1 in
        -h|--help)
            show_help
            exit
            ;;
        --skip_antismash)
            antismash_run=false
            ;;
        --agrobacterium)
            agrobacterium_run=true
            ;;
	    --skip_macsyfinder)
            macsyfinder_run=false
            ;;
	    --skip_integronfinder)
            integronfinder_run=false
            ;;
        --skip_defensefinder)
            defensefinder_run=false
            ;;
        --skip_tiger)
            tiger_run=false
            ;;
	    --skip_gapmind)
            gapmind_run=false
            ;;
        --skip_dbscan-swa)
            dbscanswa_run=false
            ;;
        --continue)
            continue_run=true
            ;;
        --gbk)
            genbank=true
            ;;
        -i|--input)
            new_input_file=$2
            input_file=$(realpath -e $new_input_file)
            new_strain=`basename $input_file`
            new_strain=`echo -e "$new_strain" | sed 's/.fna$//g;s/.fasta$//g;s/.fas$//g;s/.gbff$//g;s/.gbk$//g;s/.fa$//g;s/.genbank$//'`
            if [ ! -z $input_file ]; then
                strain=$new_strain
            fi
            shift
            ;;
        -t|--threads)
            new_thread=$2
            numberre='^[0-9]+$'
            if [[ ! $new_thread =~ $numberre ]]; then
				echo -e "The --thread argument must be a numerical value." | tee -a Beav.log
				exit
			elif [ ! -z $new_thread ]; then
				thread=$new_thread
			fi
            shift
		    ;;
        --strain)
            new_user_strain=$2
            if [ ! -z $new_user_strain ]; then
                user_strain=$new_user_strain
            fi
            shift
            ;;
        -o|--output)
            new_output=$2
            if [ ! -z $new_output ]; then
                output=$new_output
            fi
            shift
             ;;
        --bakta_arguments)
            new_bakta_args=$2
            if [ ! -z "$new_bakta_args" ]; then
                bakta_args=$new_bakta_args
            fi
            shift
            ;;
        --antismash_arguments)
			new_antismash_args=$2
            if [ ! -z "$new_antismash_args" ]; then
                antismash_args=$new_antismash_args
			fi
			shift
			;;
        --tiger_blast_database)
            new_tiger_args=$2
            if [ ! -z "$new_tiger_args" ]; then
                tiger_blast_database=$new_tiger_args
            fi
            shift
            ;;
        --run_operon_email)
            new_operon_args=$2
            if [ ! -z "$new_operon_args" ]; then
                email=$new_operon_args
                operon_run=true
            fi
            shift
            ;;            
			*) break
	 esac
    shift
done

#Checks input arguments to make sure required arguements are present and exists

if [[ -z $input_file ]];then
	echo -e "An input file is required. Please use the --input argument and run again" | tee -a Beav.log
	exit
elif [[ ! -f $input_file ]];then
	echo -e "The specified input file does not exist" | tee -a Beav.log
	exit
fi

if [[ ! -d $output ]];then
	echo -e "The specified output directory (${output}) does not exist" | tee -a Beav.log
	exit
fi

if $tiger_run;then
	if [[ -z $tiger_blast_database ]];then
		echo -e "Tiger requires a blast database as input. Please rerun using the --tiger_blast_database option or use the --skip_tiger option" | tee -a Beav.log
		exit
	fi
fi

if [ $user_strain ]; then
    strain=$user_strain
fi

echo -e "" | tee -a Beav.log
echo -e "Checking prerequisites:" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log

missing_program=false

if ! bakta -h &> /dev/null
then	
	echo "Bakta: ERROR" | tee -a Beav.log
	missing_program=true
else
	echo "Bakta: OK" | tee -a Beav.log
fi

if $antismash_run
then
    if ! antismash -h &> /dev/null
    then
        echo "antiSMASH: ERROR" | tee -a Beav.log
        missing_program=true
    else
        echo "antiSMASH: OK" | tee -a Beav.log
    fi
else
	echo "antiSMASH: skipped" | tee -a Beav.log
fi

if $macsyfinder_run
then
    if ! macsyfinder -h &> /dev/null
    then
        echo "MacSyFinder: ERROR" | tee -a Beav.log
        missing_program=true
    else 
        echo "MacSyFinder: OK" | tee -a Beav.log
    fi
else
	echo "MacSyFinder: skipped" | tee -a Beav.log
fi

if $agrobacterium_run
then
    if ! fuzznuc -h &> /dev/null
    then
        echo "EMBOSS (fuzznuc): ERROR" | tee -a Beav.log
        missing_program=true
    else
	    echo "EMBOSS (fuzznuc): OK" | tee -a Beav.log
    fi
    if ! nhmmer -h &> /dev/null
    then 
        echo "HMMER (nhmmer): ERROR" | tee -a Beav.log
        missing_program=true
    else
        echo "HMMER (nhmmer): OK" | tee -a Beav.log
    fi
fi

if $integronfinder_run
then
    if ! integron_finder -h &> /dev/null
    then
        echo "IntegronFinder: ERROR" | tee -a Beav.log
        missing_program=true
    else 
        echo "IntegronFinder: OK" | tee -a Beav.log
    fi
else
	echo "IntegronFinder: skipped" | tee -a Beav.log
fi

if $defensefinder_run
then
    if ! defense-finder --help &> /dev/null
    then
        echo "DefenseFinder: ERROR" | tee -a Beav.log
        missing_program=true
    else 
        echo "DefenseFinder: OK" | tee -a Beav.log
    fi
else
	echo "DefenseFinder: skipped" | tee -a Beav.log
fi

if $tiger_run
then
    if [[ ! -f $BEAV_DIR/software/TIGER/bin/island_finder.pl ]]
    then
        echo "TIGER2: missing" | tee -a Beav.log
        missing_program=true
    else
        echo "TIGER2: OK" | tee -a Beav.log
    fi
else
	echo "TIGER2: skipped" | tee -a Beav.log
fi

if $gapmind_run
then
    if [[ ! -f $BEAV_DIR/software/PaperBLAST/bin/gapsearch.pl ]]
    then
        echo "GapMind: missing" | tee -a Beav.log
        missing_program=true
    else
        echo "GapMind: OK" | tee -a Beav.log
    fi
	
	#if ! usearch &> /dev/null
	#then
	#	echo "usearch: ERROR"
	#else
	#	echo "usearch: OK"
	#fi
else
	echo "GapMind: skipped" | tee -a Beav.log
fi

if $dbscanswa_run
then
    if [[ ! -f $BEAV_DIR/software/DBSCAN-SWA/bin/dbscan-swa.py ]]
    then
        echo "DBSCAN-SWA: missing" | tee -a Beav.log
        missing_program=true
    else
	echo "DBSCAN-SWA: OK" | tee -a Beav.log
    fi
else
	echo "DBSCAN-SWA: skipped" | tee -a Beav.log
fi

if $missing_program;then 
	echo -e "" | tee -a Beav.log
	echo -e "Some required programs are missing or gave an error message." | tee -a Beav.log
	echo -e "Either install them or use the --skip-PROGRAM option" | tee -a Beav.log
	echo -e "Please run "beav_db" to install databases" | tee -a Beav.log
	exit
fi

echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log

mv Beav.log $output 2> /dev/null
cd $output

#Check if continue argument was used and if program output file exist, are empty, or present and not empty 

if $continue_run; then
        echo -e "Checking Bakta output" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./${strain}/bakta/${strain}.gbff ] && [ ! -f ./${strain}/bakta/${strain}.faa ] && [ ! -f ./${strain}/bakta/${strain}.gff3 ]; then
                echo -e "Bakta output files do not exist" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./${strain}/bakta/${strain}.gbff ] && [ -s ./${strain}/bakta/${strain}.faa ] && [ -s ./${strain}/bakta/${strain}.gff3 ]; then
                echo -e "Required outputs found. Skipping Bakta" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                bakta_run=false
        elif [ ! -s ./${strain}/bakta/${strain}.gbff ] && [ ! -s ./${strain}/bakta/${strain}.faa ] && [ ! -s ./${strain}/bakta/${strain}.gff3 ]; then
                echo -e "Output files are empty. Moving empty files and rerunning Bakta" | tee -a Beav.log
		echo -e "" | tee -a Beav.log
		rm -rf ./$strain
	fi
fi

if $genbank; then
     bakta_run=false
     mkdir ${strain}
     mkdir ${strain}/bakta
     cp ${input_file} ${strain}/bakta/${strain}.gbff
     python ${BEAV_DIR}/scripts/convert_gbff.py ${strain}
     mv ${strain}.faa ${strain}.gff3 ${strain}.fna ${strain}.ffn ${strain}/bakta/
fi

if $bakta_run; then 

	echo -e "Running Bakta" | tee -a Beav.log
	echo -e "" | tee -a Beav.log
	SECONDS=0
	bakta --threads "$thread" --proteins $BEAV_DIR/databases/bakta_custom_protein/combined.faa --strain "$strain" --output $strain --skip-plot --prefix "$strain" --keep-contig-headers $bakta_args $input_file > ${strain}_Bakta.log || { echo error occurred while running Bakta. Please see Bakta.log >&2; mv ${strain}_Bakta.log $strain/Bakta.log; mv Beav.log $strain; exit 1; }
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
	mkdir ${strain}/bakta
	
	mv ${strain}/${strain}.txt ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.embl ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.faa ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.faa.idx ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.ffn ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.fna ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.gbff ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.gbk ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.gff3 ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.json ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.nofasta.gff3 ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}_cds_subset.gbk ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.tsv ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.hypotheticals.faa ${strain}/bakta/ 2> /dev/null
	mv ${strain}/${strain}.hypotheticals.tsv ${strain}/bakta/ 2> /dev/null

	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
	echo -e "" | tee -a Beav.log
fi
mv ${strain}_Bakta.log ${strain}/Bakta.log 2> /dev/null
mv Beav.log $strain 2> /dev/null
cd $strain

mkdir tables 2> /dev/null



operon_skipsubmit=false
if $operon_run && $continue_run; then
        echo -e "Checking Operon-mapper output" | tee -a Beav.log
        if  [ -d ./operon-mapper_results ] && [ -f ./operon-mapper_results/list_of_operons.table ]; then
                echo -e "Output found. Skipping Operon-mapper" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                operon_run=false

        elif [ -f ./oeron-mapper_results_url ] && grep --quiet "http://biocomputo.ibt.unam.mx/operon_mapper/out" ./operon-mapper_results_url; then 
                echo -e "Operon-mapper partial results found. Checking for completed job" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
				
				jobisdone=false
				jobstillrunning=false

				URL=`tail -n1 operon-mapper_results_url`
				submitstatus=`head -n1 operon-mapper_results_url`
				jobnum=`echo -e "$URL" | sed 's/^.*out_//g;s/\.html$//g'`
				
				response=$(curl -L -s -w "%{http_code}" $URL)
				http_code=$(tail -n1 <<< "$response")  # get the last line
				content=$(sed '$ d' <<< "$response")
					
				if [[ "$http_code" -eq 200 ]] ; then
					if echo "$content" | grep -qF 'Download' ; then
						operonsurl=`echo -e "$content" | grep 'list_of_operons_' | sed 's/^.*href="//g;s/" TARGET.*//g' | sed 's#^\.\.#http://biocomputo.ibt.unam.mx/operon_mapper#g'`
						if curl --head --silent --fail $operonsurl 2> /dev/null; then
							jobisdone=true
						fi
					elif ! echo "$content" | grep -iqF 'error' ; then
						jobstillrunning=true
					fi
				fi

				if [ $jobisdone ]; then
					echo -e "Original job is complete. Downloading results at end of run." | tee -a Beav.log
					operon_run=false
				elif [  $jobstillrunning ]; then
					echo -e "Original job is still running. Checking results at end of run." | tee -a Beav.log
					operon_skipsubmit=true
				else
					echo -e "Original job did not complete or results longer available. Resubmitting Operon-mapper job." | tee -a Beav.log
					rm -f ./operon-mapper_results_url
					rm -f ./testresponse.html
				fi
        else
			#remove url and partial results
			rm -f ./operon-mapper_results_url
			rm -f ./testresponse.html
			rm -rf ./operon-mapper_results
		fi
fi
if $operon_run && ! $operon_skipsubmit; then
    echo -e "----------------------------------------------------------" | tee -a Beav.log
    echo -e "" | tee -a Beav.log
    echo -e "Submitting remote Operon-mapper job" | tee -a Beav.log
    echo -e "" | tee -a Beav.log
	echo -e "Converting input" | tee -a Beav.log
    #format gff for operon-mapper
    bp_genbank2gff3 --quiet bakta/${strain}.gbff
    if [ ! -f ${strain}.gbff.gff.gz ]; then
        gzip ${strain}.gbff.gff
    fi
    echo -e "Checking file sizes" | tee -a Beav.log
    #looks at file information and gets size in MB
    fna_file=$(ls -l --block-size=MB bakta/${strain}.fna | awk '{print $5}' | sed 's/MB//g')
    gff_files=$(ls -l --block-size=MB ${strain}.gbff.gff.gz | awk '{print $5}'| sed 's/MB//g')
    #combined file size
    sum=$(($fna_file + $gff_files))
    echo $sum | tee -a Beav.log
    #Operon-mapper max size is 38MB
    maxsize=38

    if (($sum > maxsize)); then
        echo -e ""
        echo -e "File sum is greater than 38MB. Zipping files" | tee -a Beav.log
        zip ${stain}.fna.zip bakta/${strain}.fna
        zip ${strain}.gbff.gff.zip ${strain}.gbff.gff
        #getting size of zipped files in MB
        zip_fna_file=$(ls -l --block-size=MB ${strain}.fna.zip | awk '{print $5}' | sed 's/MB//g')
        zip_gff_files=$(ls -l --block-size=MB ${strain}.gff.zip | awk '{print $5}'| sed 's/MB//g')
        zip_sum=$(($zip_fna_file + $zip_gff_files))
        if (($zip_sum < maxsize)); then
            echo -e "" | tee -a Beav.log
            echo -e "Zipped file sum is larger then 38MB. Operon-Mapper can not run" | tee -a Beav.log
            operon_run=false
        fi
    fi

fi
if $operon_run && ! $operon_skipsubmit; then
	echo -e "Submitting job to webserver" | tee -a Beav.log
    #submit operon-mapper job to webserver
    python ${BEAV_DIR}/scripts/submit_operon-mapper_job.py --email $email --strain $strain
    rm ${strain}.gbff.gff
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
	echo -e "" | tee -a Beav.log
fi

echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Annotation of other sequence elements" | tee -a Beav.log
echo -e "" | tee -a Beav.log
 
#makes genbank file with only cds regions for antismash
python $BEAV_DIR/scripts/subset_cds_genbank.py "$strain"
touch borders.log


#if continue runs redo border annotations
if $continue_run; then
    rm -rf borders
    rm -f ./tables/borders.table
    rm -f ./tables/${strain}_borders.table
    rm -f ./tables/${strain}_uniq_borders.table
fi

mkdir borders  2> /dev/null
SECONDS=0
if $agrobacterium_run; then
	nhmmer --tblout "$strain".leftborder $BEAV_DIR/models/T-DNA_leftborder.hmm bakta/"$strain".fna >> borders.log 
	nhmmer --tblout "$strain".rightborder $BEAV_DIR/models/T-DNA_rightborder.hmm bakta/"$strain".fna >> borders.log
	nhmmer --tblout "$strain".overdrive $BEAV_DIR/models/overdrive.hmm bakta/"$strain".fna >> borders.log
	fuzznuc --sequence bakta/"$strain".fna --pattern RTTDCAWWTGHAAY -outfile ${strain}.virbox -rformat excel --complement >> borders.log 2>&1
	fuzznuc --sequence bakta/"$strain".fna --pattern WNGTGMARAWYTGCACDW -outfile ${strain}.trabox -rformat excel --complement >> borders.log 2>&1
	mv ${strain}.leftborder  ./borders/${strain}.left_T-DNA_border
        mv ${strain}.rightborder  ./borders/${strain}.right_T-DNA_border
        mv ${strain}.overdrive  ./borders/
	mv ./${strain}.virbox ./borders/
	mv ./${strain}.trabox ./borders/
fi

${BEAV_DIR}/scripts/find_dif.sh bakta/${strain}.fna "$thread"
nhmmer --tblout "$strain".nodbox $BEAV_DIR/models/nodbox.hmm bakta/"$strain".fna >> borders.log
nhmmer --tblout "$strain".ttsbox $BEAV_DIR/models/ttsbox.hmm bakta/"$strain".fna >> borders.log
fuzznuc -pattern 'GGAAC[CT]N(15,17)CCACNNA' -sequence bakta/"$strain".fna -complement -outfile ${strain}.hrp_box.out -rformat excel >> borders.log 2>&1
fuzznuc -pattern 'TTCGBN(15)TTCGB' -sequence bakta/"$strain".fna -complement -outfile ${strain}.pip_box.out -rformat excel >> borders.log 2>&1
fuzznuc -pattern 'GGGNAGGG' -sequence bakta/"$strain".fna -complement -outfile ${strain}.kops.out -rformat excel >> borders.log 2>&1
fuzznuc -pattern 'GTGACANTGTCAC' -sequence bakta/"$strain".fna -complement -outfile ${strain}.matS.out -rformat excel >> borders.log 2>&1
mv ./${strain}.kops.out ./borders/
mv ./${strain}.matS.out ./borders/
mv ./${strain}.pip_box.out ./borders/
mv ./${strain}.hrp_box.out ./borders/
mv ./${strain}.nodbox ./borders/
mv ./${strain}.ttsbox ./borders/
mv ./dif.table ./borders/
touch borders.table

if $agrobacterium_run; then
	borderfiles="borders/${strain}.nodbox borders/${strain}.overdrive borders/${strain}.ttsbox borders/${strain}.left_T-DNA_border borders/${strain}.right_T-DNA_border"
else
	borderfiles="borders/${strain}.nodbox borders/${strain}.ttsbox"
fi

#format border files for bedtools and then make border table
cat $borderfiles | grep -v '#' | sed 's/\s\+/\t/g' | awk '$13 <= 0.05' | cut -f 1,3,7,8,12,13 | sort -k1,1 -k3,3g | sed 's/^\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)/\1\t\3\t\4\t\6\t\2\t\5/g' | awk '$2 > $3 { s=$2; $2=$3; $3=s } {print}' | sed 's/\s\+/\t/g' | sortBed | bedtools merge -c 4,5,6 -o collapse,collapse,distinct | while read curborderline; do
	contig=`echo -e "$curborderline" | cut -f 1`
	startpos=`echo -e "$curborderline" | cut -f 2`
	endpos=`echo -e "$curborderline" | cut -f 3`
	borderevalues=`echo -e "$curborderline" | cut -f 4`
	bordernames=`echo -e "$curborderline" | cut -f 5`
	strand=`echo -e "$curborderline" | cut -f 6`
	evallist=`echo -e "$borderevalues" | sed 's/,/\n/g'`
	namelist=`echo -e "$bordernames" | sed 's/,/\n/g'`
	newname=`echo "$namelist" | paste - <(echo "$evallist") | sort -k2,2g | head -n1 | cut -f 1`
	echo -e "$contig    $newname        $startpos       $endpos $strand" >> borders.table
done

#check if borders/promoters overlap with genes, if so, discard
cat ./bakta/${strain}.gff3 | sed -n '/^##FASTA/q;p' | sed '/region\t[0-9]/d' | grep "CDS" | grep -v "remark" > ${strain}.nofasta.gff3
cat borders.table | sed 's/\s\+/\t/g' | awk '{print $1,$3,$4,"100",$2,$5}' | sed 's/^\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)\t\(\S\+\)/\1\t\3\t\4\t\5\t\2\t\6/g' | sed 's/\s\+/\t/g' | sed 's/\t+/\t+1/g' | sed 's/\t-/\t-1/g' > borders.bed
cut -f 1-3,5 ./borders/${strain}.virbox | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\tvirbox\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed
cut -f 1-3,5 ./borders/${strain}.trabox | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\ttrabox\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed    
cut -f 1-3,5 ./borders/${strain}.pip_box.out | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\tpipbox\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed
cut -f 1-3,5 ./borders/${strain}.hrp_box.out | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\thrpbox\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed
cut -f 1-3,5 ./borders/${strain}.kops.out | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\tKOPS\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed
cut -f 1-3,5 ./borders/${strain}.matS.out | grep -v 'SeqName' | sed 's/\t\(\S\+\)$/\t100\tmatS\t\1/g' | sed 's/+/+1/g' | sed 's/\t-/\t-1/g' >> borders.bed
cat borders/dif.table >> borders.bed
awk '$2 > $3 { s=$2; $2=$3; $3=s } {print}' borders.bed | sed 's/\s\+/\t/g' > temp_border.bed
bedtools intersect -v -nonamecheck -a temp_border.bed -b ./${strain}.nofasta.gff3 > ./${strain}_borders.table
cat ${strain}_borders.table | awk '{print $1,$4,$6,$2,$3,$5}' | sort | uniq -f4 -u | awk '{print $1,$4,$5,$6,$3}' | sed 's/\s\+/\t/g' > ./${strain}_uniq_borders.table
cat ${strain}_borders.table | awk '{print $1,$4,$6,$2,$3,$5}' | sort | uniq -f4 -D | awk '{print $1,$4,$5,$6,"0"}' | uniq | sed 's/\s\+/\t/g' >> ./${strain}_uniq_borders.table

mv *.table ./tables/ 2> /dev/null
mv ./borders.bed ./borders/
mv ./temp_border.bed ./borders/
ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec" 
echo $ELAPSED | tee -a Beav.log


echo -e "" | tee -a Beav.log
echo -e "Done" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Indentifying oriT" | tee -a Beav.log
echo -e "" | tee -a Beav.log
SECONDS=0
$BEAV_DIR/scripts/find_oriT.sh bakta/${strain}.fna $thread
ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
echo $ELAPSED | tee -a Beav.log
mv oriT.table ./tables
echo -e "" | tee -a Beav.log
echo -e "Done" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log

echo -e "Identifying secretion systems (MacSyFinder)" | tee -a Beav.log
echo -e "" | tee -a Beav.log

if $continue_run && $macsyfinder_run; then
	echo -e "Checking secretion system annotations" | tee -a Beav.log
	echo -e "" | tee -a Beav.log
	if [ ! -f ./MacSyFinder_TXSS/best_solution.tsv ]; then 
		echo -e "MacSyFinder output files do not exist. Rerunning MacSyFinder" | tee -a Beav.log
		echo -e "" | tee -a Beav.log
	elif [ -s ./MacSyFinder_TXSS/best_solution.tsv ]; then
		echo -e "MacSyFinder output found. Skipping MacSyFinder" | tee -a Beav.log
		echo -e "" | tee -a Beav.log
		macsyfinder_run=false
	elif [ ! -s ./MacSyFinder_TXSS/best_solution.tsv ]; then
		echo -e "MacSyFinder output files are empty. Deleting empty files and rerunning MacSyFinder." | tee -a Beav.log 
		rm -rf MacSyFinder_TXSS
		rm ./tables/macsyfinder.tsv.table
	fi
fi

if $macsyfinder_run; then
	SECONDS=0
	python $BEAV_DIR/scripts/makegembase.py
	macsyfinder -o MacSyFinder_TXSS --db-type gembase --sequence-db allgembase.faa --worker 1 --models TXSScan all --models-dir $BEAV_DIR/models > MacSyFinder.log || error_exit "error occurred while running MacSyFinder. Please see MacSyFinder.log" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec" | tee -a Beav.log
	echo $ELAPSED | tee -a Beav.log
	cut -f 2,3 ./MacSyFinder_TXSS/best_solution.tsv | sed 's/^\S\+_//g' | sed 's/=/_/g' | grep '	' | grep -v gene_name > macsyfinder.tsv.table
	mv allgembase* ./MacSyFinder_TXSS/
	mv macsyfinder.tsv.table ./tables/ 2> /dev/null
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Identifying integrons (IntegronFinder)" | tee -a Beav.log
echo -e "" | tee -a Beav.log
if $continue_run && $integronfinder_run; then
        echo -e "Checking integron annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons ]; then
                echo -e "IntegronFinder outfiles do not exist. Rerunning IntegronFinder" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons ]; then
                echo -e "IntegronFinder output found. Skipping IntegronFinder" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                integronfinder_run=false 
        elif [ ! -s ./Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons ]; then
                echo -e "IntegronFinder output files are empty. Deleting empty files and rerunning IntegronFinder." | tee -a Beav.log
                rm -rf Integron_Finder
		rm ./tables/integron_gene.table
		rm ./tables/integron.table
        fi
fi

if $integronfinder_run; then
	SECONDS=0
	integron_finder --local-max --cpu "$thread" --outdir Integron_Finder --promoter-attI --pdf  ./bakta/"$strain".fna > Integron_Finder.log || error_exit "error occurred while running IntegronFinder. Please see Integron_Finder.log" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
 	cut -f 2-6,11 ./Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons | awk '$2 ~/P_in|att/' > integron.table
 	cat ./Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons | grep -P "\tintI\t" | cut -f 2,4-5 | bedtools intersect -a - -b ${strain}.nofasta.gff3 -wb -F 0.5 | grep "CDS" | sed -n 's/^.*locus_tag=\([a-zA-Z0-9_]*\);.*$/\1/p' > integron_gene.table 
	mv *.table ./tables/ 	
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Identifying defense systems (DefenseFinder)" | tee -a Beav.log
echo -e "" | tee -a Beav.log

if $continue_run && $defensefinder_run; then
        echo -e "Checking defense system annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./tables/${strain}_defensefinder.tsv.table ]; then
                echo -e "DefenseFinder ouput files do not exist. Rerunning DefenseFinder" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./tables/${strain}_defensefinder.tsv.table ]; then
                echo -e "DefenseFinder output found. Skipping DefenseFinder" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                defensefinder_run=false
        elif [ ! -s ./tables/${strain}_defensefinder.tsv.table ]; then
                echo -e "Defense system annotations were unsucessfull. Deleting outfiles and rerunning DefenseFinder." | tee -a Beav.log 
                rm -rf DefenseFinder
		rm ./tables/${strain}_defensefinder.tsv.table
        fi
fi

if $defensefinder_run; then
	SECONDS=0
	defense-finder run --db-type gembase ./bakta/${strain}.faa --models-dir $BEAV_DIR/models > defensefinder.log 2>&1 || error_exit "error occurred while running DefenseFinder. Please see defensefinder.log" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
	cut -f 2,3 ./${strain}_defense_finder_genes.tsv | grep -v 'hit_id' > ${strain}_defensefinder.tsv.table
	mv *.table ./tables/ 2> /dev/null
	mkdir DefenseFinder
	mv ${strain}_defense_finder_* DefenseFinder/ 2> /dev/null
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Identifying biosynthetic gene clusters (antiSMASH)" | tee -a Beav.log
echo -e "" | tee -a Beav.log

if $continue_run && $antismash_run; then
        echo -e "Checking biosyntehtic gene cluster annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./tables/${strain}_antismash.table ]; then
                echo -e "antiSMASH output files do not exist. Rerunning antiSMASH" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./tables/${strain}_antismash.table ]; then
                echo -e "antiSMASH output found. Skipping antiSMASH" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                antismash_run=false
        elif [ ! -s ./tables/${strain}_antismash.table ]; then
                echo -e "antiSMASH output files are empty. Deleting empty files and rerunning antiSMASH." | tee -a Beav.log
                rm -rf antiSMASH
		rm ./tables/${strain}_antismash.table
		rm ./tables/${strain}_antismash.table.beav.subset
        fi
fi


if $antismash_run; then
	SECONDS=0
	antismash ${strain}_cds_subset.gbk --cpus $thread --output-dir antiSMASH $antismash_args || error_exit "error occurred while running antiSMASH" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
	python $BEAV_DIR/scripts/antismash_genbanks_to_table.py -i ./antiSMASH -o ${strain}_antismash.table
	mv *.beav.subset ./tables/ 2> /dev/null
	mv *.table ./tables/ 2> /dev/null
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Identifying phage (DBSCAN-SWA)" | tee -a Beav.log
echo -e "" | tee -a Beav.log


if $continue_run && $dbscanswa_run; then
        echo -e "Checking phage annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./tables/prophage.table ]; then
                echo -e "DBSCAN-SWA output files do not exist. Rerunning DBSCAN-SWA" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./DBSCAN-SWA/bac_DBSCAN-SWA_prophage_summary.txt ]; then
                echo -e "DBSCAN-SWA output found. Skipping DBSCAN-SWA" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                dbscanswa_run=false
        elif [ ! -s ./DBSCAN-SWA/bac_DBSCAN-SWA_prophage_summary.txt ]; then
                echo -e "DBSCAN-SWA output files are empty. Deleting empty files and rerunning DBSCAN-SWA." | tee -a Beav.log 
                rm -rf DBSCAN-SWA
		rm ./tables/prophage.table
        fi
fi


if $dbscanswa_run; then
	SECONDS=0
	sed -i 's/gnl|Bakta|//g' ${strain}_cds_subset.gbk
	python $BEAV_DIR/software/DBSCAN-SWA/bin/dbscan-swa.py --input ${strain}_cds_subset.gbk --output DBSCAN-SWA --thread_num "$thread" > dbscan-swa.log || error_exit "error occurred while running DBSCAN-SWA. Please see dbscan-swa.log" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
	cut -f 2,5-8 ./DBSCAN-SWA/bac_DBSCAN-SWA_prophage_summary.txt | grep -v "bacteria_id" > prophage.table
	mv *.table ./tables/ 2> /dev/null
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Characterizing amino acid biosynthesis and small carbon metabolite catabolism (GapMind)" | tee -a Beav.log
echo -e "" | tee -a Beav.log

if $continue_run && $gapmind_run; then
        echo -e "Checking amino acid biosynthesis and small carbon metabolite cartabolism annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./GapMind/combined_GapMind_results.tab ]; then
                echo -e "GapMind output files do not exist. Rerunning GapMind" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
        elif [ -s ./GapMind/combined_GapMind_results.tab ]; then
                echo -e "GapMind output found. Skipping GapMind" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                gapmind_run=false
        elif [ ! -s ./GapMind/combined_GapMind_results.tab ]; then
                echo -e "GapMind output files are empty. Deleting empty files and rerunning GapMind." | tee -a Beav.log
                rm -rf GapMind
        fi
fi


if $gapmind_run; then
	SECONDS=0
	$BEAV_DIR/scripts/run_GapMind_aa_carbon.sh "$strain" "$thread"
	mv formatdb.log ./GapMind/
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec" | tee -a Beav.log
        echo $ELAPSED | tee -a Beav.log
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log
echo -e "Identifying integrative conjugative elements [ICEs] (TIGER2)" | tee -a Beav.log
echo -e "" | tee -a Beav.log
if $continue_run && $tiger_run && [ ! -z $tiger_blast_database ]; then
        echo -e "Checking integrative conjugative element annotations" | tee -a Beav.log
        echo -e "" | tee -a Beav.log
        if [ ! -f ./tables/${strain}_TIGER2_final.table.out ]; then
                echo -e "TIGER2 output files do not exist. Rerunning TIGER2" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
		rm -rf TIGER2
        elif [ -f ./tables/${strain}_TIGER2_final.table.out ]; then
                echo -e "TIGER2 output found. Skipping TIGER2" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                tiger_run=false
        fi
fi


if $tiger_run && [ ! -z "$tiger_blast_database" ]; then
	SECONDS=0
	$BEAV_DIR/scripts/run_TIGER2.sh "$strain" "$tiger_blast_database" "$thread" | tee -a Beav.log
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a Beav.log
	cat ./${strain}_TIGER2_final.table.out | sed 's/\s\+/\t/g' | sed 's/\telement/\ element/g' | sed 's/\t(ICE/\ (ICE/g' > tiger_cut.table
	mv *.table ./tables/ 2> /dev/null
	mv *.table.out ./tables/ 2> /dev/null
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
else
	echo -e "" | tee -a Beav.log
	echo -e "Skipped" | tee -a Beav.log
fi

echo -e "" | tee -a Beav.log
echo -e "----------------------------------------------------------" | tee -a Beav.log
echo -e "" | tee -a Beav.log

if $operon_run; then
    echo -e "Checking status of remote Operon-mapper job and downloading results" | tee -a Beav.log
    echo -e "" | tee -a Beav.log

    #check on status of operon-mapper job and wait for results
    ${BEAV_DIR}/scripts/check_operon_mapper_status.sh | tee -a Beav.log
    
    echo -e "" | tee -a Beav.log
    echo -e "----------------------------------------------------------" | tee -a Beav.log
    echo -e "" | tee -a Beav.log
fi

#if operons are present, check for vgrG clusters
if  [ -d ./operon-mapper_results ] && [ -f ./operon-mapper_results/list_of_operons.table ]; then
	
	echo -e "Identifying T6SS vgrG operons" | tee -a Beav.log
	echo -e "" | tee -a Beav.log

	${BEAV_DIR}/scripts/identify_vgrG_clusters.sh $strain | tee T6SS_vgrG_cluster_list.out | tee -a Beav.log
	
	echo -e "" | tee -a Beav.log
	echo -e "----------------------------------------------------------" | tee -a Beav.log
	echo -e "" | tee -a Beav.log
fi

if $continue_run && $agrobacterium_run; then
        echo -e "Checking Agrobacterium annotations" | tee -a Beav.log
#if all listed outputs are present then skip
        if [ -s ${strain}.agrobacteria_taxonomy.out ] && [ -s ${strain}.oncogenic_plasmid_final.out ] && [ -s ${strain}.agro_ani.out ] && [ -s ${strain}.oncogenic_plasmid_type.sketch.out ] && [ -s ${strain}.oncogenic_plasmid_final.out.contiglist ] && [ -s ${strain}.oncogenic_plasmid_contigs.sketch.out ]; then
                agrobacterium_run=false
		echo -e "Outfiles found. Skipping Agrobacterium pipeline" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                echo -e "T-DNA borders:" | tee -a Beav.log
                echo -e "contig start   end     border  strand" | tee -a Beav.log
                grep 'T-DNA' borders/borders.bed | cut -f 1,2,3,5,6 | tee -a Beav.log
                echo "" | tee -a Beav.log
                echo "" | tee -a Beav.log
                echo "oncogenic plasmid type: (best hit reference strain)" | tee ${strain}.oncogenic_plasmid_final.out | tee --append oncogenicplasmid.log | tee -a Beav.log
                grep 'WKID' -A 1 ${strain}.oncogenic_plasmid_type.sketch.out | tail -n 1 | sed 's/^.*\s//g' | sed 's/__/\t/g' | tee -a ${strain}.oncogenic_plasmid_final.out | tee --append oncogenicplasmid.log | tee -a Beav.log
                echo "" | tee -a ${strain}.oncogenic_plasmid_final.out | tee --append oncogenicplasmid.log | tee -a Beav.log
                echo "oncogenic plasmid-like contigs: (best hit reference strain)" | tee -a ${strain}.oncogenic_plasmid_final.out | tee --append oncogenicplasmid.log | tee -a Beav.log
                echo "contig    length  weighted_k-mer_id       k-mer_id        plasmid_type    best_hit_ref_strain" | tee -a ${strain}.oncogenic_plasmid_final.out | tee --append oncogenicplasmid.log | tee -a Beav.log

                grep 'WKID' ${strain}.oncogenic_plasmid_contigs.sketch.out -A1 -B1 | grep -v '^--$' | grep -v 'WKID' | sed 's/^Query: //g' | sed 's/\s.*Bases: /___BASES___/g' | sed 's/\s.*File:.*$//g' | paste -d " " - - | sed 's/\s\+/\t/g' | cut -f 1,2,3,14 | sed 's/___BASES___/\t/g' | sed 's/__\(\S\+\)$/\t\1/g' | tee -a ${strain}.oncogenic_plasmid_final.out | tee ${strain}.oncogenic_plasmid_final.out.contiglist | tee --append oncogenicplasmid.log
                echo -e "" | tee -a Beav.log
                echo -e "Done" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                echo -e "----------------------------------------------------------" | tee -a Beav.log
                echo -e "" | tee -a Beav.log

                echo -e "Outfiles found. Skipping Agrobacterium pipeline" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
#if any listed outputs are empty,then move all the outputs and rerun the agro pipeline
        elif [ ! -s ${strain}.agrobacteria_taxonomy.out ] || [ ! -s ${strain}.oncogenic_plasmid_final.out ] || [ ! -s ${strain}.agro_ani.out ] || [ ! -s ${strain}.oncogenic_plasmid_type.sketch.out ] || [ ! -s ${strain}.oncogenic_plasmid_final.out.contiglist ] || [ ! -s ${strain}.oncogenic_plasmid_contigs.sketch.out ]; then
                echo -e "Agrobacterium pipeline outputs are empty. Removing files and rerunning Agrobacterium pipeline" | tee -a Beav.log
                echo -e "" | tee -a Beav.log
                rm -f ./${strain}.agro_ani_out ./${strain}.agrobacteria_taxonomy.out ./${strain}.oncogenic_plasmid_final.out ./${strain}.oncogenic_plasmid_final.out.contiglist ./${strain}.oncogenic_plasmid_type.sketch.out ./${strain}.oncogenic_plasmid_contigs.sketch.out
#if any of the listed outputs do not exist, then rerun the pipeline
        elif [ ! -f ${strain}.agrobacteria_taxonomy.out ] || [ ! -f ${strain}.oncogenic_plasmid_final.out ] || [ ! -f ./${strain}.agro_ani.out ]; then
                echo -e "Agrobacterium pipeline files not found. Rerunning Agrobacterium pipeline" | tee -a Beav.log
		echo -e "" | tee -a Beav.log
        fi
fi

if $agrobacterium_run; then
    echo -e "Characterizing Agrobacterium lineage and Ti/Ri plasmid sequences" | tee -a Beav.log
    echo -e "" | tee -a Beav.log

    $BEAV_DIR/scripts/check_agrobacteria_biovar.sh "$strain" "$thread" | tee -a Beav.log
   	
	echo -e "" | tee -a Beav.log
	
	$BEAV_DIR/scripts/identify_Ti_Ri_plasmid_contigs.sh "$strain".fna | tee -a Beav.log

    echo -e "" | tee -a Beav.log
    echo -e "T-DNA borders:" | tee -a Beav.log
	echo -e "contig	start	end	border	strand" | tee -a Beav.log
	grep 'T-DNA' borders/borders.bed | cut -f 1,2,3,5,6 | tee -a Beav.log
	
	echo -e "" | tee -a Beav.log
	echo -e "Done" | tee -a Beav.log
    echo -e "" | tee -a Beav.log
    echo -e "----------------------------------------------------------" | tee -a Beav.log
    echo -e "" | tee -a Beav.log
fi
mv ${strain}_cds_subset.gbk ./bakta 2> /dev/null
mv ${strain}.gbff.gff.gz ./bakta 2> /dev/null
mv ${strain}.nofasta.gff3 ./bakta 2> /dev/null
echo -e "Combining annotations and preparing final output files" | tee -a Beav.log
SECONDS=0
cd ..
python $BEAV_DIR/scripts/combine_annotations.py "$strain" 
ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
echo -e "" | tee -a ${strain}/logs/Beav.log
echo $ELAPSED | tee -a ${strain}/Beav.log
#convert gbk to gff3 format
bp_genbank2gff3 --quiet --noinfer ${strain}/${strain}_final.gbk -out stdout | sed '/^##FASTA$/,$d' > ${strain}/${strain}_final.no_fasta.gff3
cp ${strain}/${strain}_final.no_fasta.gff3 ${strain}/${strain}_final.gff3
cat ${strain}/bakta/${strain}.fna | sed 's/ .*//g' >> ${strain}/${strain}_final.gff3



rm ${strain}/genomelist 2> /dev/null


mkdir ${strain}/logs 2> /dev/null
${strain}/${strain}.log >> ${strain}/logs/Bakta.log 2> /dev/null
mv ${strain}/*.log ${strain}/logs/ 2> /dev/null
mv ${strain}/${strain}_final.no_fasta.gff3 ${strain}/bakta 2> /dev/null
mv ${strain}/${strain}_final.oncogenic.gbk ${strain} 2> /dev/null
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "Final annotation output: ${strain}_final.gbk" | tee -a ${strain}/logs/Beav.log
echo -e "" | tee -a ${strain}/logs/Beav.log

if $circos_run; then
	SECONDS=0
	echo -e "----------------------------------------------------------" | tee -a ${strain}/logs/Beav.log
        echo -e "" | tee -a ${strain}/logs/Beav.log
        echo -e "Creating Circos Map" | tee -a ${strain}/logs/Beav.log
	echo -e "" | tee -a ${strain}/logs/Beav.log
	$BEAV_DIR/scripts/beav_circos.sh "$output"/"$strain"
	ELAPSED="Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec"
	echo $ELAPSED | tee -a ${strain}/logs/Beav.log
	echo -e "" | tee -a ${strain}/logs/Beav.log
	echo -e "Done" | tee -a ${strain}/logs/Beav.log
        mv ${strain}.circos.png ${strain}
        mv ${strain}.circos.pdf ${strain}
        mv ${strain}.oncogenes.png ${strain}
        mv ${strain}.oncogenes.pdf ${strain}
	mv ${strain}.oncogenic.gbk ${strain}
fi
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "----------------------------------------------------------" | tee -a ${strain}/logs/Beav.log
echo -e "Summary of annotations" | tee -a ${strain}/logs/Beav.log
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "Secretion_Systems      Defense_Systems Phages  Biosynthetic_gene_clusters      ICEs    Integrons" | tee ./${strain}/summary.table | tee -a ${strain}/logs/Beav.log
if [ -f ${strain}/MacSyFinder_TXSS/all_systems.tsv ]
then
        secretion_systems=` cat ${strain}/MacSyFinder_TXSS/all_systems.tsv | cut -f 5 | sort | uniq | grep -v "#" | grep -v "model_fqn" | sed '/^[[:space:]]*$/d' | wc -l `
else
        secretion_systems="N/A"
fi

if [ -f ${strain}/DefenseFinder/${strain}_defense_finder_systems.tsv ]
then
        defense_systems=` cat ${strain}/DefenseFinder/${strain}_defense_finder_systems.tsv | cut -f 2 | grep -v "type" | sort | uniq | wc -l `
else
        defense_systems="N/A"
fi

if [ -f  ${strain}/tables/prophage.table ]
then
        phages=` cat ${strain}/tables/prophage.table | cut -f 5 | sort | uniq | wc -l `
else
        phages="N/A"
fi
if [ -f ${strain}/tables/${strain}_antismash.table.beav.subset ]
then
        antiSMASH=` cat ${strain}/tables/${strain}_antismash.table.beav.subset | grep -v "cluster" | cut -f 2 | sort | uniq | wc -l `
else
        antiSMASH="N/A"
fi
if [ -f ${strain}/Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons ]
then
        integrons=` cat ${strain}/Integron_Finder/Results_Integron_Finder_${strain}/${strain}.integrons | cut -f 1 | grep -v "ID_integron" | grep -v "#" | uniq | wc -l `
else
        integrons="N/A"
fi

if [ -f ${strain}/tables/tiger_cut.table ]
then
        ice=` cat ${strain}/tables/tiger_cut.table | uniq | wc -l `
else
        ice="N/A"
fi

if [ -f ${strain}/GapMind/carbon.sum.rules ]
then
        gap_mind=` cat ${strain}/GapMind/carbon.sum.rules | cut -f 5,4,7-8 | grep "all" | awk '$4 == 0' | awk '$3 == 0' | cut -f 1 | sort | uniq | awk 'BEGIN { ORS = ", " } { print }' | sed 's/,\s\+$//g'`
else
        gap_mind="N/A"
fi
echo -e "${secretion_systems}   ${defense_systems}      ${phages}       ${antiSMASH}    ${ice}  ${integrons}" | tee --append ./${strain}/summary.table | tee -a ${strain}/logs/Beav.log

echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "Small carbon catabolism pathways: ${gap_mind}" | tee --append ./${strain}/summary.table | tee -a ${strain}/logs/Beav.log

if [ -f ${strain}/${strain}.oncogenic_plasmid_final.out ]
then
        plasmid_type=`cat ${strain}/${strain}.oncogenic_plasmid_final.out | sed -n "2p"`
        echo -e "" | tee -a ${strain}/logs/Beav.log
        echo -e "Agrobacterium plasmid type: ${plasmid_type}" | tee --append ./${strain}/summary.table | tee -a ${strain}/logs/Beav.log
fi



echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "Done" | tee -a ${strain}/logs/Beav.log
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "----------------------------------------------------------" | tee -a ${strain}/logs/Beav.log
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "The BEAV pipeline automates the use of a number of published software tools." | tee -a ${strain}/logs/Beav.log
echo -e 'If you use these results in a publication, please include the following in your methods section and cite:' | tee -a ${strain}/logs/Beav.log
echo -e "" 

echo -e "Jung J, Rahman A, Schiffer A, and Weisberg A. 2023. BEAV: a bacterial genome and mobile element annotation pipeline. https://github.com/weisberglab/beav" | tee -a ${strain}/logs/Beav.log 
echo -e ""
bakver=`grep 'version' $output/${strain}/logs/bakta.log | head -n1 | sed 's/^.*version=//g'` | tee -a ${strain}/logs/Beav.log
echo -e "Bakta version $bakver" | tee -a ${strain}/logs/Beav.log
echo -e "Schwengers O, Jelonek L, Dieckmann MA, et al. 2021. Bakta: rapid and standardized annotation of bacterial genomes via alignment-free sequence identification. Microb Genom 7: 000685." | tee -a ${strain}/logs/Beav.log
echo -e "" | tee -a ${strain}/logs/Beav.log
echo -e "EMBOSS:fuzznuc" | tee -a ${strain}/logs/Beav.log
echo -e "EMBOSS: The European Molecular Biology Open Software Suite (2000) Rice,P. Longden,I. and Bleasby,A. Trends in Genetics 16, (6) pp276--277 " | tee -a ${strain}/logs/Beav.log

if $macsyfinder_run; then
	macver=`head -n1 $output/${strain}/MacSyFinder_TXSS/macsyfinder.log | sed 's/^.*Macsyfinder //g'` 
	echo -e "MacSyFinder version $macver" | tee -a ${strain}/logs/Beav.log
    echo -e 'Néron, Bertrand; Denise, Rémi; Coluzzi, Charles; Touchon, Marie; Rocha, Eduardo P.C.; Abby, SophieS 2023. MacSyFinder v2: Improved modelling and search engine to identify molecular systems igenomes. Peer Community Journal, Volume 3, article no. e28. DOI: 10.24072/pcjournal.250.' | tee -a ${strain}/logs/Beav.log
fi
echo -e "" | tee -a ${strain}/logs/Beav.log

if $dbscanswa_run; then
	echo -e "DBSCAN-SWA" | tee -a ${strain}/logs/Beav.log
    echo -e 'Gan R, Zhou F, Si Y, et al. 2022. DBSCAN-SWA: An Integrated Tool for Rapid Prophage Detection and Annotation. Frontiers in Genetics 13.' | tee -a ${strain}/logs/Beav.log
fi
echo -e "" | tee -a ${strain}/logs/Beav.log

if $tiger_run; then
	echo -e "TIGER version 2.1.0" | tee -a ${strain}/logs/Beav.log
	echo -e 'Mageeney CM, Lau BY, Wagner JM, et al. 2020. New candidates for regulated gene integrity revealed through precise mapping of integrative genetic elements. Nucleic Acids Research 48: 4052-65.' | tee -a ${strain}/logs/Beav.log
fi
echo -e "" | tee -a ${strain}/logs/Beav.log

if $defensefinder_run; then
	echo -e "DefenseFinder" | tee -a ${strain}/logs/Beav.log
    echo -e 'Tesson F., Hervé A. , Touchon M., d’Humières C., Cury J., Bernheim A. Systematic and quantitative view of the antiviral arsenal of prokaryotes bioRx' | tee -a ${strain}/logs/Beav.log
fi
echo -e "" | tee -a ${strain}/logs/Beav.log

if $integronfinder_run; then
	intver=`grep 'version' $output/${strain}/Integron_Finder/Results_Integron_Finder_${strain}/integron_finder.out | head -n1 | sed 's/^.*version //g'`
	echo -e "IntegronFinder version $intver" | tee -a ${strain}/logs/Beav.log
    echo -e 'Néron B, Littner E, Haudiquet M, et al. 2022. IntegronFinder 2.0: Identification and Analysis of Integrons across Bacteria, with a Focus on Antibiotic Resistance in Klebsiella. Microorganisms 10: 700.' | tee -a ${strain}/logs/Beav.log
fi 
echo -e "" | tee -a ${strain}/logs/Beav.log

if $antismash_run; then
	antversion=`grep 'antiSMASH version' $output/${strain}/antiSMASH/index.html | sed 's/^.*version //g'`
	echo -e "antiSMASH version $antversion" | tee -a ${strain}/logs/Beav.log
    echo -e 'Kai Blin, Simon Shaw, Alexander M Kloosterman, Zach Charlop-Powers, Gilles P van Weezel, Marnix H Medema, & Tilmann Weber. 2021. Nucleic Acids Research DOI:10.1093/nar/gkab335.' | tee -a ${strain}/logs/Beav.log
fi
echo -e "" | tee -a ${strain}/logs/Beav.log

if $gapmind_run; then
	echo -e "GapMind" | tee -a ${strain}/logs/Beav.log
	echo -e "Amino acid biosynthesis:" | tee -a ${strain}/logs/Beav.log
    echo -e 'Price MN, Deutschbauer AM, and Arkin AP. 2020. GapMind: Automated Annotation of Amino Acid Biosynthesis. mSystems 5: e00291-20.' | tee -a ${strain}/logs/Beav.log
	echo -e "Catabolic pathways:" | tee -a ${strain}/logs/Beav.log
    echo -e 'Price MN, Deutschbauer AM, and Arkin AP. 2022. Filling gaps in bacterial catabolic pathways with computation and high-throughput genetics. PLOS Genetics 18(4): e1010156. DOI:10.1371/journal.pgen.1010156' | tee -a ${strain}/logs/Beav.log
fi

if $operon_run; then
    echo -e "Operon-mapper" | tee -a ${strain}/logs/Beav.log
    echo -e "Taboada B, Estrada K, Ciria R, and Merino E. Operon-mapper: a web server for precise operon identification in bacterial and archaeal genomes, Bioinformatics, Volume 34, Issue 23, December 2018, Pages 4118–4120, https://doi.org/10.1093/bioinformatics/bty496" | tee -a ${strain}/logs/Beav.log
fi
