#!/bin/csh 

############################################################### 
#   tlsanl: to correct B factors (B_total = B_residual + B_tls),
#     when the following conditions are satisfied
#     a). The PDB coordates were refined by REFMAC
#     b). When TLS was involved in refinement
#     c). When the residue ranges are correct (so that tlsanl works).
#     d). The ANISOU record do not exist in coordinates (no B correction yet)
#     e). The B_total are in the correct range
##################### Usage ################################## 
#  tlsanl_script.csh  pdbfile
##################### Do TLSAN ###############################

if( $#argv <1 ) then
    echo "Please input a PDB file. "
    echo "Usage: tlsanl_script.csh  pdbfile"
    exit()
endif

set pdbfile=$1
set refmac=`grep "^REMARK   3   PROGRAM " -m 1 $pdbfile | awk '{print $5}' `  
if( $refmac !~ "REFMAC" ) then
    echo "Structure not refined by REFMAC, No TLS correction is applied)!"
    exit()
endif

set aniso=`grep "^ANISOU" -m 2 $pdbfile | wc -l  | awk '{print $1}' ` 
if ( $aniso >1 ) then
    echo "ANISOU record exist! no tls correction was applied!"
    exit()
endif


#extract tls from PDB
set tls_inp = "${pdbfile}_tls.inp"
tlsextract XYZIN $pdbfile TLSOUT $tls_inp >/dev/null

set size=`wc -l $tls_inp  | awk '{print $1}'`
if( ! -e $tls_inp ||  $size <= 6 ) then
    /bin/rm -f $tls_inp
    exit()
endif


# do tlsan to get a new pdb
echo "Doing TLSAL to get a new PDB file"
set tlspdb="${pdbfile}_tls"
set tlslog="${pdbfile}_tls.log"
tlsanl XYZIN  $pdbfile  TLSIN  $tls_inp  XYZOUT  $tlspdb <<end >$tlslog
BRESID t 
end

set size=`wc -c $tlspdb  | awk '{print $1}'`
if( -e $tlspdb && $size > 2000 ) then
    set tmpfile="tmpfile"
    echo "TLSAL was successful!"
#    awk '($1 !~ /ANISOU/) {print $0}' $tlspdb > $tmpfile  #strip ANISOU
#    /bin/mv -f  $tmpfile  $tlspdb 
endif

#rm -f $tls_inp 

