#!/bin/bash -e

# This is a quick-and-dirty fix to change the angle involving the "O2"
# atom when the atom type is not "O".

# It is supposed to run after fix_CTER script and assumes the presence
# of "O2".

# This fix assumes that an atom named "O1" indicates a
# C-terminal residue, which is true for plain proteins but not
# necessarily for other systems (that may contain other atoms named
# "O1").
#

# This could have been added to fixCTER script but this part is only
# necessary to build the dictionary file while fixCTER is always needed
# to build the initial topology.

# ATTENTION: This is specific to the G54A7 force field.


[[ $# -ne 1 || ${1##*.} != top ]] && \
    echo -e "Error: Usage: fixCTER some.top\nSpecific for G54A7!" && \
    exit 1

awk '
BEGIN{
  top=ARGV[1];
}
$0~/\[ atoms \]/, $1=="" { if ($5=="O1") ctres[$3]=1 }
END{
  while(getline<top)
  {
    if($0~/\[ atoms \]/) a=1 ;
    if(a && ctres[$3])
    {
      if ($5=="CA") ca[$1]=1; if ($5=="C") ct[$1]=1 ;
      if ($5=="O2") ga[$1] = ($2=="OM") ? 22 : ($2=="OA") ? 19 : 0 ;
    }
    if($1=="") a=0 ;
    if($0~/\[ angles \]/) ang=1 ;
    if(ang && ga[$3] && ca[$1] && ct[$2])
      s=sprintf("%5d %5d %5d %5d    ga_%d ; changed by fixCTER_angle", $1, $2, $3, $4, ga[$3]) ;
    else s=$0 ;
    print s > "_aux.top" ;
    if (ang && $1=="") {ang=0; delete ca; delete ct; delete ga} ;
  }
}
' $1 
cp _aux.top $1
rm _aux.top 

exit 0

############################################################################
