#!/bin/bash

ARGUMENTS=$(getopt \
               --options ht:p:r: \
               --longoptions help,type:,prefix:,refseq: \
               --name 'ratt' -- "$@"
        )

if [ $? != 0 ]
then
    echo "See ratt(1) for usage information."
    exit 1
fi

eval set -- "$ARGUMENTS"


while true
do
    case "$1" in
       -h|--help)
           cat /opt/gensoft/exe/ratt/1.0.3/man/cat1/ratt.1
           exit 0
           ;;
       -t|--type)
           parameterSet="$2"
           shift 2
           ;;
       -p|--prefix)
           result="$2"
           shift 2
           ;;
       -r|--refseq)
           ref="$2"
           shift 2
           ;;
       --)
           shift
           break
           ;;
       *)
           echo "Support for option $1 is not implemented. Ignoring..."
           ;;
    esac
done

refembl=$1
query=$2

if [ -z "$RATT_HOME" ]; then
 echo "Please set the RATT_HOME variable."
 echo "At Sanger for bash it is RATT_HOME=/nfs/users/nfs_t/tdo/Bin/ratt; export RATT_HOME"
 echo "At Sanger for tcsh setenv RATT_HOME /nfs/users/nfs_t/tdo/Bin/"

 echo "I will use the sanger default!"
RATT_HOME=/nfs/users/nfs_t/tdo/Bin/ratt; export RATT_HOME
fi;

### parameter of nucmer
D=5
NUCMER_PATH=$PAGIT_HOME/bin/;

## check that required arguments are passed
if [ -z "$refembl" ] \
       || [ -z "$query" ] \
       || [ -z "$parameterSet" ] \
       || [ -z "$result" ]
then
       echo "A required option was not passed. See ratt(1) for usage information"
       exit 1
fi

if [ ! -z "$RATT_VERBOSE" ]
	then
	verbose=1;
fi

if [ -z "$RATT_DOTRANSLATION" ] ;
	then
	RATT_DOTRANSLATION=0	
fi

### nucmer call as function
function doNucmer {
sleep 10
	if [ ! -z "$verbose" ] 
		then 
		echo "nucmer  $other_nucmer  -g $g -p $name -c $c -l $l $ref $query"
		echo "delta-filter $rearrange -i $minInd $name.delta > $name.filter.delta"
	fi
	echo  nucmer $other_nucmer -D $D -g $g -p $name -c $c -l $l $ref $query
	nucmer $other_nucmer -g $g -p $name -c $c -l $l $ref $query  # &> /dev/null
	delta-filter $rearrange -i $minInd $name.delta > $name.filter.delta
	show-snps -HTr $name.filter.delta > $name.snp
	show-coords -clHT $name.delta > $name.coords
	show-coords -clHT $name.filter.delta > $name.filter.coords
}

function doiCORN {


	echo " embl file are in embl_DIR
 	root is $root
    pre_embl is $pre_embl
    iteration is $iteration
"

	echo "================="
	cd "$root$(($iteration-1))"

	cd "$root$(($iteration-1))"
	

	# geneate the plot
	mkdir plot
	echo "Producing the coverage plots in $root$iteration"
#	awk '{ if ($1 ~ "^cons") {print $4 > "plot/"x"."$2".plot"}}' x=Iter.$iteration <(gunzip -c *pileup.gz)
	cd ..
	mkdir -p RATT.$iteration/Seq
	cd RATT.$iteration/Seq

	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Split ../../$root.$iteration
	
	cd ..
	ln -s ../$root$(($iteration-1))/plot

	tmp=$$;
	ln -s ../$embl_DIR embl.$tmp

	mkdir tmp
	for x in `grep '>' ../$root.$iteration | sed 's/>//g' | awk '{ print $1 }'` ; do
		cat ../$root.*.$x.gff > ../All.$x.gff;
		egrep "\"INS|\"DEL"  ../All.$x.gff | sort -n -k 4 > tmp/All.indel.$x.gff; 
		echo "/opt/gensoft/adm/bin/perl $RATT_HOME/ratt.icorn.pl embl.$tmp/$x.embl tmp/All.indel.$x.gff $x $x.embl 4000000"
		/opt/gensoft/adm/bin/perl $RATT_HOME/ratt.icorn.pl  embl.$tmp/$x.embl tmp/All.indel.$x.gff $x $x.embl 4000000 > out;
echo "/opt/gensoft/adm/bin/perl ~/Bin/icorn.flagNonCorrectedRegions.pl Seq/$x plot/Iter.$iteration.$x.plot $x 20 100 Not+Corrected"
		/opt/gensoft/adm/bin/perl ~/Bin/icorn.flagNonCorrectedRegions.pl Seq/$x plot/Iter.$iteration.$x.plot $x 20 100 Not+Corrected;
		
	done;


}

if [ "$refembl" == "iCORN" ] ; then 
	refembl=$2;
	query=$3
	result=$4
#	doiCORN;
#	echo done;
#	exit;
	parameterSet="Assembly"
fi

### check path of nucmer and the /opt/gensoft/adm/bin/perl transferprogram
NUCMER_EXE=${NUCMER_EXE-`which nucmer 2>/dev/null`}
EMBL_files=${EMBL_files-`ls $refembl/ | wc 2>/dev/null`}
#PERL_SCRIPT=${NUCMER_EXE-`which samtools 2>/dev/null`}
if (test "$NUCMER_EXE" == "");
then
   echo "nucmer is not on the PATH"
   exit; 
elif(test "$EMBL_files" == "");
then
   echo "Cannot find any EMBL files in $refembl is not on the PATH."
   echo "So far just embl formatted files can be used. They must end with .embl."
   exit; 
fi

tmp=$$;

# check for the query
if [ ! -f "$query" ]                # be sure the directory /mnt exists
  then
    echo "Query $query doesn't exist"
	exit
fi

# get weird character aways
sed 's/|/_/g' $query > query.$tmp
query=query.$tmp
orig_query=$query

# check for the reference
if [ -f "$ref" ] 
	then 
	# if the reference exist, use this
	echo "I am using the reference $ref. Please make sure that the description line of each fasta entry is the same than in the embl file name!";
	head -n 1 $ref
	echo "should be the same name as the embl file in embl"
	ls $refembl
	echo
	echo
else
	ref="Reference.$tmp.fasta"
	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Embl2Fasta $refembl $ref
fi
	
### check if files ok
if [ ! -f "$ref" ]                # be sure the directory /mnt exists
  then
    echo "Sorry the reference file wasn't generated corretly."
	exit
fi;

name=nucmer.$result

### paramters to set for the nucmer
# l - "k-mer size" 10 short 20 assembly set
# c - cluster size
# g - extending of cluster

# rearrange = set for delta-filter -1    1-to-1 alignment allowing for rearrangements
#                                  -g    1-to-1 global alignment not allowing rearrangements



doneDifference=0;

# minInd - minimal indentity
# minLength - minlength of a hit   -- not used so far...

if [ "$parameterSet" == "Assembly" ] || [ "$parameterSet" == "Assembly.Repetitive" ] ;
	then 
	c=400;
	l=30;
	g=1000;
	
	if [ "$parameterSet" == "Assembly.Repetitive" ] ;
		then
		other_nucmer=" --maxmatch "
	else
		other_nucmer="  "
	fi
#       rearrange=" -g -o 0 ";
	rearrange=" -r -o 5 ";
	minInd=99;
	
	### get real SNP before mutate
	doNucmer 

	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
	doneDifference=1;

	### insert of mutation to have better anchors
	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Mutate $query
	return=$?
	if [ "$return" != "0" ] ;
		then 
		echo "See Error in BBA.main script, to mutate the query for Assembly to Assembly annotation transfer."
		exit 1;
	fi;
	### update name of query
	query=$query."mutated"
elif [ "$parameterSet" == "Pacbio" ] ;
       then
        c=800;
        l=30;
        g=2000;

        if [ "$parameterSet" == "Pacbio.Repetitive" ] ;
                then
                other_nucmer=" --maxmatch "
        else
                other_nucmer="  "
        fi
        rearrange=" -1 -o 20 -l 2000 ";
        minInd=98;
	other_nucmer="  -diagdiff 10 "
        ### get real SNP before mutate
        doNucmer

        /opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
        doneDifference=1;

        ### insert of mutation to have better anchors
        /opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Mutate $query
        return=$?
        if [ "$return" != "0" ] ;
                then
                echo "See Error in BBA.main script, to mutate the query for Assembly to Assembly annotation transfer."
                exit 1;
        fi;
        ### update name of query
        query=$query."mutated"
elif [ "$parameterSet" == "PacbioG" ] ;
       then
        c=800;
        l=30;
        g=2000;

        if [ "$parameterSet" == "Pacbio.Repetitive" ] ;
                then
                other_nucmer=" --maxmatch "
        else
                other_nucmer="  "
        fi
        rearrange=" -g -o 20 -l 5000 ";
        minInd=98;
        other_nucmer="  -diagdiff 10 "

        ### get real SNP before mutate
        doNucmer

        /opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
        doneDifference=1;

        ### insert of mutation to have better anchors
        /opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Mutate $query
        return=$?
        if [ "$return" != "0" ] ;
                then
                echo "See Error in BBA.main script, to mutate the query for Assembly to Assembly annotation transfer."
                exit 1;
        fi;
        ### update name of query
        query=$query."mutated"
elif [ "$parameterSet" == "Falciparum" ] ||  [ "$parameterSet" == "Falciparum.Repetitive" ] ;
	then 
	c=400;
	l=150;
	g=2000;

	if [ "$parameterSet" == "Falciparum.Repetitive" ] ;
		then
		other_nucmer=" --maxmatch "
	else
		other_nucmer="  "
	fi
	
	rearrange=" -r -o 1 ";
	minInd=90;
	
	### get real SNP before mutate
#	doNucmer

#	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
	doneDifference=0;

	### insert of mutation to have better anchors
#	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Mutate $query
#	return=$?
#	if [ "$return" != "0" ] ;
#		then 
#		echo "See Error in BBA.main script, to mutate the query for Assembly to Assembly annotation transfer."
#		exit 1;
#	fi;
	### update name of query
#	query=$query."mutated"

elif [ "$parameterSet" == "Strain" ] ||  [ "$parameterSet" == "Strain.Repetitive" ] || [ "$parameterSet" == "Strain.global" ] ||  [ "$parameterSet" == "Strain.global.Repetitive" ];
	then 
	c=400;
	l=20;
	g=500;

	if [ "$parameterSet" == "Strain.Repetitive" ] || [ "$parameterSet" == "Strain.global.Repetitive" ] ;
		then
		other_nucmer=" --maxmatch "
	else
		other_nucmer="  "
	fi
minInd=90;	
	rearrange=" -r -o 1 ";
	if  [ "$parameterSet" == "Strain.global" ] ||  [ "$parameterSet" == "Strain.global.Repetitive" ] ;
		then
		rearrange=" -g -o 15 ";
                minInd=95;
		D=10	
fi


	
	### get real SNP before mutate
	doNucmer

	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
	doneDifference=1;

	### insert of mutation to have better anchors
	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Mutate $query
	return=$?
	if [ "$return" != "0" ] ;
		then 
		echo "See Error in BBA.main script, to mutate the query for Assembly to Assembly annotation transfer."
		exit 1;
	fi;
	### update name of query
	query=$query."mutated"

elif [ "$parameterSet" == "Species" ]  || [ "$parameterSet" == "Species.Repetitive" ] || [ "$parameterSet" == "Species.global" ]  || [ "$parameterSet" == "Species.global.Repetitive" ] ;
	then 
	if [ "$parameterSet" == "Species.Repetitive" ] ;
		then
		other_nucmer=" --maxmatch "
	else
	other_nucmer="  -diagdiff 10 "		
#other_nucmer="  "
	fi

	c=400;
	l=10;
	g=1000;
	minInd=40;
 
	rearrange=" -r -o 5 ";
	if  [ "$parameterSet" == "Species.global" ]  || [ "$parameterSet" == "Species.global.Repetitive" ] ;
		then
		rearrange=" -g -o 5 ";
	fi
elif [ "$parameterSet" == "Multiple" ] ;
	then 
	c=400;
	l=25;
	g=1000;
	
	other_nucmer=" --maxmatch "
	rearrange=" -q -o 1";
	minInd=98;
elif [ "$parameterSet" == "Free" ] ;
	then 
	c=$RATT_c;
	l=$RATT_l;
	g=$RATT_g;
	rearrange=$RATT_rearrange;
	minInd=$RATT_minInd;
	other_nucmer=$RATT_anchor;
else
	echo "Plese set: Transfer type: Assembly / Strain / Species / Strain.Repetitive / Strain.global / Species.Repetitive / Species.global / Free "
	exit
fi


### do the comparison using nucmer
doNucmer

# print the synteny stats and do the difference files.
if [ "$doneDifference" == "0" ]
	then 
	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Difference  $name.snp $name.filter.coords $result
fi

### do the tranfer
if [ ! -z "$verbose" ] 
	then
	echo "Nucmer is done. Now transfer the annotation."
	echo "/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl $refembl $name.snp $name.filter.coords $result"
fi

/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Transfer $refembl $name.snp $name.filter.coords $result
return=$?
if [ "$return" != "0" ] ;
	then 
	echo "Sorry, the RATT transfer step did fail.\n"
	echo "Debug information: /opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Transfer $refembl $name.snp $name.filter.coords $result";
	pwd
	exit 1;
fi;

### do ther correction
# first the fasta
mkdir Sequences
tmp=$$
ln -s $orig_query tmpSeqXXX.$tmp
cd Sequences
/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Split ../tmpSeqXXX.$tmp
cd ..
rm tmpSeqXXX.$tmp

echo "Nucmer is done. Now Correct the annotation for chromosome $nameRes."


for nameRes in `grep '>' $query | /opt/gensoft/adm/bin/perl -nle 's/\|/_/g;/>(\S+)/; print $1'` ; do
	echo "work on $nameRes"
	if [ -f "$result.$nameRes.embl" ] ; then
		echo "************************ Correction *****"
		/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl Correct $result.$nameRes.embl Sequences/$nameRes $result.$nameRes
	echo "************************ "
	else 
		### generate empty file for the joining 
		touch $result.$nameRes.tmp2.embl
	fi

	/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl doEMBL $result.$nameRes.final $result.$nameRes.tmp2.embl Sequences/$nameRes 
	if [ "$RATT_DOTRANSLATION" -eq 1 ] ; then
		/opt/gensoft/adm/bin/perl $RATT_HOME/main.ratt.pl addTranslation $result.$nameRes.final.embl
	fi
	echo "If you want to start artemis on this replicon:"
	echo "art $result.$nameRes.final.embl + $result.$nameRes.Report.gff  + Query/$result.$nameRes.Mutations.gff"

done

rm $result*embl.tmp.BBA.embl # $result.$nameRes.tmp2.embl

