receptor_pdbqt=$1
receptor_pdbqt_modified=$2
receptor_pdbqt_modified2=$3
ligand_pdbqt=$4
size_x=$5
out=$6
log=$7
receptor_name=$8
ligand_name=$9
receptor_file=${10}
receptorTypes=${11}
toolsDirectory=${12}

MYRAND=$(( ( RANDOM % 10000000 )  + 1 ))
RANDDIR=${MYRAND}


# ENABLE PROTEIN CODE
proteinCode=$(echo ${13} | awk '{print toupper($0)}')

# ENABLE PROTEIN CODE
#PROTEINDB=${YOUR_PATH_TO_FOLDER_DB}
PROTEINDB=/home/galaxy-bitlab/proteindb



mkdir $RANDDIR


cp -r ${toolsDirectory}/scripts/* $RANDDIR

cp $receptorTypes $RANDDIR
NOMBRERECEPTOR=$(basename $receptorTypes)
mv $RANDDIR/$NOMBRERECEPTOR $RANDDIR/receptor_atm_types.txt

MYPWD=$PWD


cd $RANDDIR

source ADT_VENV/bin/activate

(Rscript pdbcenter_npts_finder.R $receptor_pdbqt_modified2 $MYPWD/$RANDDIR) 2>&1

(Rscript gpffilemaker.R $receptor_pdbqt_modified2 $MYPWD/$RANDDIR) 2>&1

(Rscript glgfilemaker.R $receptor_pdbqt_modified2 $MYPWD/$RANDDIR) 2>&1

echo "[INFO] Working path: $PWD"


proteinPath=$PROTEINDB/$proteinCode
echo "[INFO] - Extracting protein code [$proteinPath]"
isRandomID="FALSE"
if [ "$proteinCode" == "X__OC__PROTEINCODE__CC__" ]
then
	isRandomID="TRUE"
	echo "No protein code supplied"
fi

filloutsNum=0
filloutsAreGood=1
if [ -d "$proteinPath" ] && [ $isRandomID == "FALSE" ]; then

	for x in {10..600..10}
	do
	        filloutsNum=$(ls -lh $PROTEINDB/$proteinCode/FILL_${x}out* 2> /dev/null | wc -l)
		if [ $filloutsNum -eq 0 ]; then
			filloutsAreGood=0
			echo "[INFO] Did not find fillout $x"
		fi
	done
else
	filloutsAreGood=0
fi

if [ -d "$proteinPath" ] && [ $filloutsAreGood -eq 1 ] && [ $isRandomID == "FALSE"  ]; then
	echo "[INFO] Found protein in database. Reusing envelopes."
	cp $proteinPath/FILL* .
else
	echo "[INFO] Did not find protein in database. Computing envelopes."
	pathLigand=$(which AutoLigand.py)
	(Rscript envelopesmaker.R $receptor_pdbqt_modified2 $MYPWD/$RANDDIR $pathLigand) 2>&1
	mkdir $proteinPath
	cp FILL* $proteinPath

fi


(Rscript clusterfilemaker.R $MYPWD/$RANDDIR) 2>&1

(Rscript clusterfinder_Auto.R $MYPWD/$RANDDIR) 2>&1

(Rscript cluster_to_vina_cluster.R $receptor_pdbqt_modified2 $ligand_pdbqt $out $log $size_x $MYPWD/$RANDDIR $receptor_name $ligand_name) 2>&1


rm -rf ./CONDA_RDKIT_ENV
rm -rf ./ADT_VENV

cd $MYPWD


deactivate
