## Scrip for converting the three bead per residue model to all atoms
## Usage: bash write_allatom.py input.bpl rna_cg.pdb
## input.bpl is in the same format as input to RNA2D3D
## rna_cg.pdb is the pdb file from cafemol output


# exit when any command fails
set -e

## load python2
module load python/2.7
#Add  the $PYTHONPATH
#export PYTHONPATH="$PATH:$analysisPath"/cg2aa"
export PYTHONPATH=$PYTHONPATH:$analysisPath"/cg2aa" 


input_bpl=$1
pdb=$2
pdb_base=`basename ${pdb%.*}`

## First, split the pdb based on chain ids
python $analysisPath"/cg2aa/split_chain.py" $pdb
#echo $pdb_base 
pdbs=`ls "${pdb_base}""_"*".pdb"`
#echo $pdbs

echo "Copying database dir to current dir"
rm -rf db
cp -r $analysisPath"/cg2aa/db" ./

[ -f "combined_allatom.pdb" ] && rm "combined_allatom.pdb"
counter=0
for file in $pdbs;
do
  echo "Now checking if any mismatch between the basepair file and pdb file sequence"
  echo "###################### Check any mismatch error here ############################"
  python $analysisPath"/cg2aa/check_seq.py" $input_bpl $file
  echo "#########################################"
  echo "Now converting 3 bead to 1 bead per residue"
  python $analysisPath"/cg2aa/make_globCM.py" $file
  python $analysisPath"/cg2aa/replace.py" "rna_ini.pdb"
  ## First change ran2d3d input to G2G input
  echo "Now making inut to G2G"
  python $analysisPath"/cg2aa/parserG2GINPUT.py" $input_bpl

  ## All atom conversion using G2G
  echo "Now doing all atom conversion using G2G"
  python $analysisPath"/cg2aa/explicit.py" "g2g_input.inp" "rna_ini.pdb" $analysisPath"/cg2aa/nt-templ.pdb"
  #cat "rna_ini-allatom.pdb" >> "combined_allatom.pdb" 
  let counter=counter+1
  #echo $counter
  if [[ $counter -eq 1 ]]
  then
     python $analysisPath"/cg2aa/replace_chainid.py" rna_ini-allatom.pdb "A"
  elif [[ $counter -eq 2 ]]
  then
     python $analysisPath"/cg2aa/replace_chainid.py" rna_ini-allatom.pdb "B"
  fi
 
  cat "rna_ini-allatom.pdb" >> "combined_allatom.pdb" 
done
