#!/bin/bash

# (c) 15/05/01: ISOT (S. Parkin, University of Kentucky)
# 
# A bash script that sets all anisotropic thermal parameters in a SHELXL14 *.RES 
# file to isotropic.  This is often useful as a precursor to modelling extensive 
# disorder.  It averages Uii (but ignores Uij) as an approximation to Ueq.  That  
# should be good enough for most purposes.  NOTE:  It does not deal with special 
# cases, such as when 'free variables' have been used for Uii.  Isot is run from 
# the command line as follows:
#
# isot filename
# 
# Where 'filename' does not include the '.res' extension.  It writes a file with 
# extension '.ueq' that can be changed to '.ins' or '.res' as needed.
#

# Use just the filename stem. If there is already a file with a '.ueq' extension 
# then remove it.  Changes the internal field separator (IFS) to a '.' so it can 
# split the filename at the '.' if an extension was specified.
#
IFS='.' 
read -r filename extension <<< "$1"
if [ -f $filename".ueq" ]; then
  rm $filename".ueq"
fi

# Change internal field separator to '^', which is a character that has no place 
# in a typical .RES file so should be safe to use. 
#
IFS='^'

# Read the file line by line. If the line has an "=" sign in it but doesn't have 
# "TITL", "REM ", "FVAR", "MPLA", or "    " as the first four characters, assume 
# the line has atom coordinates and that it continues on the next line. If other  
# commands that might include continuation crop up, they can be accounted for by  
# inclusion in the 'if' statement below, separated by a '^' character (if '^' is 
# the internal field separator, IFS). On atom lines that run over two lines take 
# the 7th and 8th fields (i.e. U11 and U22), as well as the first field from the 
# next line (U33).  These are averaged using 'bc', and are used as the Ueq value 
# in the new file.  That's an approximation, but it is probably good enough.  To 
# calculate it properly would require orthogonalizing and diagonalizing each Uij 
# matrix, and there hardly seems much point in that.
#
while read line
do
if [[ "$line" =~ [=] ]] && [[ "TITL^REM ^FVAR^MPLA^    " != *"${line:0:4}"* ]]; then
  u11=`echo "$line" | awk -F ' ' '{print $7}'`
  u22=`echo "$line" | awk -F ' ' '{print $8}'`
  read nextline
  u33=`echo "$nextline" | awk -F ' ' '{print $1}'`
  ueq="0"$(bc <<< "scale=3; (($u11 + $u22 + $u33) / 3)")"00"
  line="`echo ${line:0:59}"$ueq"`"
fi
echo "$line" >> $filename".ueq"

done < $filename.res

echo
echo " A file named "$filename".ueq has been written - rename to .ins as needed."
echo
