#!/bin/tcsh

setenv DOKKUMDIR /data/vdbedem/qFitRun/DOKKUMDIR
setenv LOOPTK_RESOURCEDIR ${DOKKUMDIR}/LOOPTK/resources/
source /home/sw/rhel5/x86_64/phenix/phenix-1.8-1069/phenix_env
setenv LD_LIBRARY_PATH ${DOKKUMDIR}/coin-Cbc/lib:$LD_LIBRARY_PATH
setenv LD_LIBRARY_PATH /home/vdbedem/DEV/ModelBuildTool/MBT/QFIT/ILOG/CPLEX_Studio_AcademicResearch122/cplex/lib/x86-64_sles10_4.1/static_pic/:/home/vdbedem/DEV/ModelBuildTool/MBT/QFIT/ILOG/CPLEX_Studio_AcademicResearch122/concert/lib/x86-64_sles10_4.1/static_pic/:$LD_LIBRARY_PATH
source /home/sdcsoftware/linux/ccp4-6.0.2/include/ccp4.setup
setenv ILOG_LICENSE_FILE /home/vdbedem/DEV/ModelBuildTool/MBT/QFIT/ILOG/CPLEX_Studio_AcademicResearch122/licenses/access.ilm

if ( ! -d $LSB_JOBINDEX ) then
  mkdir $LSB_JOBINDEX
endif

set CURRLOC = $PWD/$LSB_JOBINDEX

if ( ! -d /scratch/$user ) then
  mkdir -p /scratch/$user
endif

set TMPDIR=`mktemp -d -p /scratch/$user` || exit 1

cp $1 ${TMPDIR}/in.pdb
cp $2 ${TMPDIR}/in.hkl
cp ../minocc.txt ${TMPDIR}

cd $TMPDIR


phenix.pdbtools in.pdb modify.rename_chain_id.old_id=$3 modify.rename_chain_id.new_id=$3 > pdbtools_rename.log
#pdbset xyzin in.pdb xyzout in.pdb << eopdb > pdbset.log
#$chain $3 $3
#end
#eopdb

$DOKKUMDIR/TRUNCATE/truncateSC in.pdb out_{$3}{$LSB_JOBINDEX}.pdb $3 $LSB_JOBINDEX

# DETERMINE RESOLUTION AND (AN)ISOTROPIC REFINEMENT
set resrange = `phenix.mtz.dump in.hkl | grep "Resolution range:"`
set res = `echo $resrange[4] | cut -c 1-5`
set res1000 = `echo $res | awk '{tot = $1*1000}{print tot }'`

if ( $res1000 < 1450 ) then
  set adp = "all"
else
  set adp = "chain $3 and resid $LSB_JOBINDEX"
endif

set paramfile = {$3}{$LSB_JOBINDEX}adp.params

echo "refinement {" > $paramfile
echo "  electron_density_maps {" >> $paramfile
echo "    map_coefficients {" >> $paramfile
echo "      mtz_label_amplitudes = FWT" >> $paramfile
echo "      mtz_label_phases = PHWT" >> $paramfile
echo "      map_type = 2mFo-DFc" >> $paramfile
echo "    }" >> $paramfile
echo "  }" >> $paramfile
echo "  refine {" >> $paramfile
echo "    strategy = *individual_sites *individual_adp" >> $paramfile
echo "    adp {" >> $paramfile
echo "      individual {" >> $paramfile
echo "        anisotropic = $adp" >> $paramfile
echo "      }" >> $paramfile
echo "    }" >> $paramfile
echo "  }" >> $paramfile
echo "}" >> $paramfile

phenix.refine in.hkl out_{$3}{$LSB_JOBINDEX}.pdb --overwrite $paramfile $4 $5

uname -a > {$3}{$LSB_JOBINDEX}resolve.log
echo `pwd` >> {$3}{$LSB_JOBINDEX}resolve.log

$DOKKUMDIR/qFit out_{$3}{$LSB_JOBINDEX}_refine_001.pdb out_{$3}{$LSB_JOBINDEX}_refine_001.mtz $3 $LSB_JOBINDEX >> {$3}{$LSB_JOBINDEX}qFit.log

rm *.map *.geo elbow*

rm in.hkl in.pdb

cp * ${CURRLOC}
