#!/bin/csh
#  script which allows to scale EFPs
#
#  usage:
#
#  scale_efp filename
#
#  The backslashes (\) are actually newline escapes because the
#  shell wants to see one command in a line
# 
#
if ($#argv < 1) then
    echo "Usage: scale_efp filename"
    exit 1
endif
if (! -r $1 || -d $1) then
    echo "File $1 does not exist or is not readable or it is a directory"
    exit 1
endif
set FILENM=$1
#
#  start the awk
#
awk '\
BEGIN{\
     sumneg=0\
     sumpos=0\
     i=1\
     }\
{\
   name[i]=$1\
#   getline\
   charge1[i]=$2\
   charge2[i]=$3\
   charge[i]=charge1[i]+charge2[i]\
   {if(charge[i]<0)\
       sumneg=sumneg+charge[i]\
   else\
       sumpos=sumpos+charge[i] }\
   i=i+1\
}\
END{\
   newtotalq=0\
   newfile=FILENAME ".scaled"\
   num=i-1\
   totalq=sumneg+sumpos\
   print "number of EFP points " num\
   print "sum of the negative charges " sumneg\
   print "sum of the positive charges " sumpos\
   print "total charge " totalq\
#  round off to the nearest whole number\
   {if(totalq>0)\
        round=int(totalq+0.5)\
   else\
        round=int(totalq-0.5)}\
   print "the total charge after scaling will be " round\
#  solve the quadratic equation for coef\
#  sumpos*coef^2 - round*coef + sumneg = 0\
   discrim=round*round-4*sumneg*sumpos\
   coef1=(-round+sqrt(discrim))/(2*sumpos)\
   coef2=(-round-sqrt(discrim))/(2*sumpos)\
   {if(coef1<0)\
      coef=-coef1\
   else\
      coef=-coef2}\
   invcoef=1/coef\
   print "positive charges will be scaled by " coef\
   print "negative charges will be scaled by " invcoef\
   print "the scaled efp monopoles are written to file " newfile\
   for(i=1;i<=num;i++)\
       {\
          {if(charge[i]>0)\
              charge[i]=charge[i]*coef\
           else\
              charge[i]=charge[i]*invcoef}\
#  charge2 does not change since it is a nuclear charge\
          charge1[i]=charge[i]-charge2[i]\
          printf("%-10s%15.10f%9.5f\n",name[i],charge1[i],charge2[i]) > newfile\
          newtotalq=newtotalq+charge[i]\
       }\
   printf("Check: the total charge is now %12.8f\n",newtotalq)\
   }  #end of END\
  ' $1

