#!/bin/ksh
#
#  bayesdiff -- does Bayesian differencing on two CNS output files
#               and writes the output to a third CNS input file.
#               The CNS output files should be written in the order
#                  FOBS SIGMA FCALC TEST
#               where FCALC is complex (default for CNS).
#               The output of this script (and the input to the next
#               round of CNS) will be named bayesdiff.hkl unless you
#               specify otherwise.  The output defines the following
#               columns of "mutant" data that you should read in to CNS
#               and use:
#                  FOBS SIGMA WEIGHT TEST
#               A log of the SOLVE run called bayesdiff.log will also
#               be created.
#
#  Usage: bayesdiff ../wt/wildtype.hkl  ../mut/mutant.hkl [output.hkl]
#
#  Author:  JB  25 Sep 99
#

#
# Check arguments
#
if [[ $# < 2 ]]; then
  echo "Usage: bayesdiff ../wt/wildtype.hkl  ../mut/mutant.hkl [output.hkl]"
  exit 0
fi
if [ -r $1 ] ; then
   wtfile=$1
else
   echo "Can't read wild-type input file $1"
   exit 0
fi
if [ -r $2 ] ; then
   intfile=$2
else
   echo "Can't read mutant input file $2"
   echo "Can't read mutant input file $2"
   exit 0
fi
outfile=${3:-bayesdiff.hkl}

#
# strip header lines at top and get rid of non-numeric parts of
# CNS file before reading it in
#
nskip=7 # number of lines to skip at the top of the file
tail +$nskip $wtfile | tr -d '[=][:alpha:]'| tr -s '[:blank:]' '[:blank:]'  > wtin.dat
tail +$nskip $intfile | tr -d '[=][:alpha:]'| tr -s '[:blank:]' '[:blank:]'  > intin.dat

#
# file up SOLVE, setting it to overwrite any output files that may exist
# from previous rounds
#
CCP4_OPEN=unknown; /usr/local/bin/solve <<EOF

logfile bayesdiff.log
SYMFILE /usr/local/lib/solve/p63.sym
CELL 61.08  61.08  110.40  90.0   90.0  120.0
RESOLUTION 20.0 2.25

IMPORT
wtin.dat
2,
wt.drg
conversion of ground-state data 
5
Fobs
Sigma
Fcalc
Phi
Rtest
1.0,
y
n
y
1
4

IMPORT
intin.dat
2,
int.drg
conversion of intermediate data from X-PLOR
5
Fobs
Sigma
Fcalc
Phi
Rtest
1.0,
y
n
y
1
4

FILEMERGE
2
wt.drg
int.drg
combined.drg
ground state and intermediate data merged into same file
1
1,3
2
1,3
2
5,5
0


infile combined.drg 
outfile tmpout.dat
ncolfowt 1
ncolswt 2
ncolfc 3
ncolfomut 4
ncolsmut 5
ncolfcmut 6
ncolrtest 7
fdiff
EOF

#
# fix up header of output file for CNS
#
set -A nreflection `wc -l tmpout.dat`
echo " NREFlection=    $nreflection">$outfile
cat <<EOF >>$outfile 
 ANOMalous=FALSe { equiv. to HERMitian=TRUE}
 DECLare NAME=FOBS                   DOMAin=RECIprocal   TYPE=REAL END
 DECLare NAME=SIGMA                  DOMAin=RECIprocal   TYPE=REAL END
 DECLare NAME=WEIGHT                 DOMAin=RECIprocal   TYPE=REAL END
 DECLare NAME=TEST                   DOMAin=RECIprocal   TYPE=INTE END
EOF
cat tmpout.dat >>$outfile
rm -f wt.dat *.drg tmpout.dat intin.dat wtin.dat


#  END OF bayesdiff.ksh 

