####  AFMcc, rmsf, residue residue correlation, and generate related text files.
####  Calculation of PDB files that score top x percent in AFMcc, and generate their pseudo images
####  Usage: bash analyze_all.sh cafe_infile atom_type top_percent
####  atom_type = choose one (sugar, phosphate, base)
####  The cafe_infile should contain full path to the output folder, pdb path, etc
###############################################################################
# Help                                                                         #
################################################################################
Help()
{
   # Display Help
   echo "Plot afmCC, rmsf, residue residue correlation, and generate related text files"
   echo "Extract PDB files that score top N percent in afmCC, and generate their pseudo images"
   echo
   echo "Usage: "
   echo "      bash analyze_all_monomer_short.sh cafe_infile atom_type top_percent"
   echo 
   echo "      cafe_infile     cafemol input file used for calculation"
   echo "      atom_type       choose one (sugar, phosphate, base, all)"
   echo "      top_percent     interger number for extracting PDBs that score top N percent in afmCC"
   echo
   echo "      The files afmcc.txt, rmsf.txt, bio3d_plots.pdf are generated in the working directory" 
   echo "      A new folder top_N%_CC_pdbs is created, which contains all results on  top N% pdbs"
   echo "      cafe_infile should contain full path to the output folder containing dcd, timestep file, and ninfo filepath"
   echo "      In the absence of ninfo file, simply point to an empty ninfo file with i_go_native_read_style = 2 in cafe_infile"
}
# Get the options
while getopts ":h" option; do
   case $option in
      h) # display Help
         Help
         exit;;
   esac
done
# While no arguments
if [[ $# -eq 0 ]] ; then
    Help
    exit 0
fi

cafe_infile=`readlink -f $1`
atom_type=$2
top_percent=$3
pdb_dir="top_"$top_percent"%_CC_pdbs"

module load R/4.0
module load python/3.5
echo "########## Now generating analysis plots and data files ################"
Rscript $analysisPath"/analysis2/analysis_bio3d.R" $cafe_infile $atom_type
echo "########## Now plotting the timestep file ##############################"
Rscript $analysisPath"/analysis2/plot_timestep.R" $cafe_infile
mkdir -p $pdb_dir
top_pdb_path=`readlink -f $pdb_dir`
# cd $pdb_dir
echo "########## Now generating the PDB files that score top $top_percent percent in the AFMcc ###############"
Rscript $analysisPath"/analysis2/write_dcd2pdb.R" $cafe_infile $top_percent $top_pdb_path
echo "######### Now generating pseudo images from the top $top_percent percent PDBs ##############"
bash $analysisPath"/analysis2/map_pdb2image_monomer.sh" $cafe_infile  $top_pdb_path
echo "######### Done with the analysis, check folder $pdb_dir ############"
