#! /bin/csh

#    PIEDA result grabber
#       version 1.0
# written Feburary 7, 2007
#   Dmitri G. Fedorov
#         AIST
# creates one file for each of the 4 interaction components for a given fragment
# Required FMO version: 3.0 and up.
# Arguments: 1) fragment number, 2) GAMESS FMO output file
# Output: CSV files that can be directly read by either GNUplot or Excel.
# example:
# piedares 3 FMOtuto.out
#
if($# != 2 || ! -e $2) then
  echo GAMESS output should be the only argument.
  exit
endif
set tmp1=$2:r.tmp1
set tmp2=$2:r.tmp2
grep "^[0-9 ][0-9 ][0-9 ][0-9 ][0-9][0-9 ][0-9 ][0-9 ][0-9 ][0-9] [NCMS][1-9]" <$2 >$tmp1
set ncols=`head -1 <$tmp1 | wc -w`
set i=1
set n=5
if($ncols < 13) set n=4
set names=`echo tot es ex ct di`
while ($i <= $n)
@ col=$i + 8 
  set fn=$2:r.$names[$i].csv
   awk <$tmp1 -v my=$1 -v c=$col '{ a=$1==my?$2:$2==my?$1:0; if(a!=0) printf "%4d,%7.2f,%8.4f,%9.3f\n",a,$5,$6,$c }' >$tmp2 
   echo $1 0 0 0 | awk -v my=$1 -v c=$col '{ printf "%4d,%7.2f,%8.4f,%9.3f\n",my,$5,$6,$c }' >>$tmp2
   sort -n <$tmp2 >$fn
@ i++
end 
   awk <$tmp1 -v my=$1 '{ a=$1==my?$2:$2==my?$1:0; if(a!=0) printf "%4d,%7.2f,%8.4f,%9.3f,%9.3f,%9.3f,%9.3f,%9.3f\n",a,$5,$6,$9,$10,$11,$12,$13 }' >$tmp2 
   echo $1 0 0 0 0 0 0 0 | awk -v my=$1 -v c=$col '{ printf "%4d,%7.2f,%8.4f,%9.3f,%9.3f,%9.3f,%9.3f,%9.3f\n",my,$5,$6,$9,$10,$11,$12,$13 }' >>$tmp2
   sort -n <$tmp2 >$2:r.all.csv
rm -f $tmp1 $tmp2
