###############################################################################
# Help                                                                         #
################################################################################
Help()
{
   # Display Help
   echo "Carry out the glob to all atom conversion and xplor refinement"
   echo
   echo "Usage: "
   echo "      bash master_aa_dimer.sh input.bpl cgRNA_list_file"
   echo 
   echo "      input.pdb         base pair list file"
   echo "      cgRNA_list_file   file containging full path of a list of cg PDBs"
   echo "                        example at scripts_path/cg2aa/cgPDB_list.txt"
   echo "                        glob to allatom conversion and Xplor refinement is iterated for each PDB"
   echo "                        The refined PDB files have the format refine_**.pdb, will produce 5 PDBs per refinement"
   echo
}
# 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

module load python/2.7
module load Xplor-NIH/3.3

bpl_file=`readlink -f $1`
cgPDB_file=$2
bpl_basename=`basename $bpl_file`
#echo $bpl_basename

## parse/process the list of pdb files 
count=1
while IFS= read -r line
do
  pdb_basename=`basename $line`
  pdb_noExt=`basename ${line%.*}`
  pdb_folder=$pdb_noExt"_"$count
  pdb_path=`readlink -f $line`
  echo "currently working on folder: " $pdb_folder
  mkdir -p $pdb_folder && cd $_
  cp $pdb_path ./
  cp $bpl_file ./
  #echo $pdb_basename
  ######## glob to all atom conversion
  echo "****** now carrying out all atom conversion ********"
  bash $analysisPath"/cg2aa/write_allatom_dimer.sh" $bpl_basename $pdb_basename
  ## increase the counter
  ((count=count+1))
 
  ##### Xplor refinement/batch job submission
  mkdir -p "refine" && cd $_
  cp $analysisPath"/cg2aa/refine_dimer.py" ./
  cp $analysisPath"/cg2aa/genDist.py" ./
  echo "******* now submitting job for all atom refinement *********"
  slurmXplor -ntasks=5 -omp 4 -to-sbatch --mem-per-cpu=20g --partition=multinode --time=1-00:00:00 refine_dimer.py -inputfiles "../combined_allatom.pdb"  "../"$pdb_basename "../"$bpl_basename

  ## get out into the top level directory
  cd ../../

done <$cgPDB_file

