#!/usr/bin/awk -f 
# This program symmetrizes ESP charges
#  the file is derived form tpg orac fle with the following format:
#  one line per atom
#  atom-id   atom-type  ESP_charge  i_num
#  where i_num is a charge number that is the same for EQUIVALENYT atoms. Viz. 
#
# c1     ct    0.145549  1
# h11    hc    0.040281  2
# h12    hc   -0.072894  2
# h13    hc   -0.072894  2
# c2     ct    0.063903  1
# h21    hc   -0.003845  2
# h22    hc    0.024253  2
# h23    hc    0.024253  2
#  
# In the example above the charges are derived from a Gaussian ESP output 
# and must be symmetryzed with respect to the two (ct and hc) equivalent atoms.
BEGIN{
    if(ARGC==1){
	print " This program symmetrizes ESP charges"
	print " "
	print " Syntax: "
	print "      symetrize_ESP_charges file_charge"
	print " "
	print "  The file 'file_charge' is derived form tpg orac fle with the following format:"
	print "  one line per atom"
	print "  atom-id   atom-type  ESP_charge  i_num"
	print "  where i_num is a charge number that is the same for EQUIVALENT atoms. Viz. "
	print ""
	print " c1     ct    0.145549  1"
	print " h11    hc    0.040281  2"
	print " h12    hc   -0.072894  2"
	print " h13    hc   -0.072894  2"
	print " c2     ct    0.063903  1"
	print " h21    hc   -0.003845  2"
	print " h22    hc    0.024253  2"
	print " h23    hc    0.024253  2"
	print "  "
	print " In the example above the charges are derived from a Gaussian ESP output "
	print " and must be symmetryzed with respect to the two (ct and hc) equivalent atoms."
	exit
    }
}
{ old_charg[NR]=$3; charge[$4] += $3; num[$4]+= 1; aindex[NR]=$4; lab[NR]= $1; typ[NR]=$2}
END {
    if(ARGC==1) {exit}
    for(i=1; i<=NR; i++) {
	indx =aindex[i]
	chg=charge[indx]/num[indx]
	printf "%-10s%-10s%10.6f%10.6f\n", lab[i],typ[i],chg,old_charg[i] 
    }      		       
}      
