#! /bin/csh -f
#
# usage: valid_xplor <basename> <residue # correction>
#
# --- evaluate input arguments ---

if ($#argv == 0) then
  echo
  echo "no base filename specified! - terminating"
  echo "Usage: valid_xplor <basename> <res correction (optional)>"
  echo
  exit
else if ($#argv == 1) then
  set basename=$argv[1]
  echo "== using base filename $basename"
#  echo "== using existing residue numbering"
else if ($#argv == 2) then
  set basename=$argv[1]
  set renum=$argv[2]
  echo "== using base filename $basename"
  echo "== adjusting residue numbers by $renum"
endif


#Edit CYSS out of PDB file
cp $basename.pdb $basename-in.pdb
sed 's/CYSS/CYS /' ./$basename-in.pdb | sed 's/ARG+/ARG /' | sed 's/LYS+/LYS /' |\
sed 's/HIS+/HIS /' | sed 's/ASP-/ASP /' | sed 's/GLU-/GLU /'> ./temp.pdb
echo "==Converting residue names and spacing the PDB file."


#Renumber PDB file
echo "==Renumbering the PDB file."
pdb_renumber_nochain.pl $renum temp.pdb > $basename-final.pdb
mv $basename-final.pdb ..
rm temp.pdb

#Renumber UPL file
echo "==Renumbering the $basename.upl file."
sort -n $basename.upl > $basename-in.upl
upl_renumber.pl $renum $basename-in.upl > $basename-final.upl
mv $basename-final.upl ..

#Renumber ACO file
echo "==Renumbering the $basename.aco file."
grep -v '#'  $basename.aco > $basename-in.aco
aco_renumber.pl $renum $basename-in.aco > $basename-final.aco
mv $basename-final.aco ..

#Renumber BMRB file
echo "==Renumbering the $basename.bmrb file."
cp  $basename.bmrb  $basename-in.bmrb
bmrb_renumber.pl $renum $basename-in.bmrb > $basename-temp.bmrb
sed 's/        0   -1     0                   0.000  0.000/ /' $basename-temp.bmrb > $basename-final.bmrb
rm $basename-temp.bmrb
mv $basename-final.bmrb ..

#Generate signle restraint file
echo "==Generating single restraint file."
cat header1  ../$basename-final.aco header2  ../$basename-final.upl > $basename-final.cons
mv $basename-final.cons ..
rm $basename-in.*

#Generate mmcif file
echo "==Generateing mmcif file."
pdb_extract -iENT ../$basename-template -iPDB ../$basename-final.pdb -NMR -o ../$basename-final.mmcif
maxit -i ../$basename-final.mmcif -o 2 -exchange_in
mv $basename-final.mmcif.pdb ..
