#! /usr/bin/awk -f

# post-process ORAC output, printing out selected properties 
#  in a "t  prop1(t) prop2(t) ... " format 

# syntax: post-out P="<name1> [<name2> ...]"  <orac-out-file>
         
#        Tstep    =      36.000 Total    =  -26367.747 TotPot   =  -29477.308
#        Coulom   =  -29314.312 Recipr   =  -26264.063 NonBond  =  -32446.655
#        Ener14   =   -2538.063 Bonded   =    2969.347 Stretch  =    1193.537
#        Angle    =    1428.790 I-Tors   =        .000 P-Tors   =     347.020
#        TotTemp  =       230.6 ResTemp  =   .2284E+03 TraTemp  =   .2502E+03
#        TotPre   =      430.33 ConPre   =      397.60 KinPre   =       32.73
#        TmpPre   =      118.80 Volume   =    11399.72 PV       =       .6865
#        .....  cell parameters  ....             ....       stress    .....
# XYZ    22.1444    28.5236    36.6359       -12.2915      19.9183     -10.7456
# ABC    90.0000    94.5000    90.0000        41.6307      -2.0115       7.0727
#       ........   ........   ........         1.8540     -12.5907     -11.0415

# {print}

# put the name of requested properties in p[]
#   using regexp for property names is not 100% safe
NR==1 {    
    sw=0;
    n=split(P,p)
#    printf "#    t    "
#    for (i=1;i<=n;i++) {
#	printf "%10s ",p[i];
#    }
#    printf "\n"
}


/\+\/-/       {next}     # skip averages 


/Tstep    =/ {if (sw==1) { printout(); sw=0} }
END          {if (sw==1) { printout(); sw=0} }

# a temporary patch 
#/Tstep    = / {gsub("Tstep    = ","Tstep    =")};


# A line containing properties
##           Tstep    =      36.000 Total    =  -26367.747 TotPot   =  -29477.308   
/^           ........ =............ ........ =............ ........ =............/ {
###/^................... = / {  
###/^ +[A-z]+[A-z0-9-]* += *[0-9\.-]+ [A-z]+[A-z0-9-]* += *[0-9\.-]+ [A-z]+[A-z0-9-]* += *[0-9\.-]/ {  
    sw=1;                     # switch printing on
    for (i=1;i<=NF;i++) {
	if ($i == "=") {
	    name=$(i-1); a[name]=$(i+1)
	}
    }
}

/XYZ/ {
    sw=1;                     # switch printing on
    a["a"]=$2;a["b"]=$3;a["c"]=$4;
}

/ABC/ {
    sw=1;                     # switch printing on
    a["alpha"]=$2;a["beta"]=$3;a["gamma"]=$4;
}


# print a footer with property names
END  {
    printf "#    t     "
    for (i=1;i<=n;i++) {
	for (name in a) {
#			  if (name==p[i]) {printf "%11.3f ",a[name]}
	    if (match(name,p[i])) {printf "%11s ",name}
	}
    }
    printf "\n"
}



# at the second empty line, print selected properties
#^ *$/ && sw>0 {sw++}

	      function printout() {
		  printf "%11.3f ",a["Tstep"];
		  for (i=1;i<=n;i++) {
		      for (name in a) {
#			  if (name==p[i]) {printf "%11.3f ",a[name]}
			  if (match(name,p[i])) {printf "%11.3f ",a[name]}
		      }
		  }
		  printf "\n"
	      }
	      
