#!/usr/local/bin/perl
# -*-Perl-*-
# This script averages table property files and puts the output into standard
# output.

# Author: Robert E. Bruccoleri
# Bristol-Myers Squibb Pharmaceutical Research Institute
# November 3, 1995
#
# Usage: avgtable [-ave] [-sd] files
#
# The default is average.
#

$flags = ":ave:sd:";
$valued_options = ":cutoff:";

&process_arguments("");

exit(1) if ($errcnt > 0);
if ($opt_ave == 0 & $opt_sd == 0) {
    $opt_ave = 1;
}

$head_st = ($opt_ave == 1 ? "AVE" : $opt_sd == 1 ? "SD" : "UNKNOWN");

while (@ARGV) {
    $arg = shift @ARGV;
    open(IN, "< $arg") || die "Unable to open $arg\n";
    $filecount += 1;
    while (<IN>) {
	print $_ if $filecount == 1;
	last if /^\*\s*$/;
    }
    $_ = <IN>;
    print "$head_st-$_" if $filecount == 1;
    $_ = <IN>;
    print "$head_st $_" if $filecount == 1;
    $_ = <IN>;
    print $_ if $filecount == 1;
    chop;
    $nrec = $_ + 0;
    $_ = <IN>;
    print $_ if $filecount == 1;
    die "Unable to parse format" unless /^\(\s*(\d+)X,F(\d+)\.0\)$/;
    ($keyw, $nw) = ($1, $2);
#    print "File: $arg  key width = $keyw  number width = $nw  nrec = $nrec\n";
    $count = 0;
    while (<IN>) {
	last if ++$count > $nrec;
	($key, $n) = unpack("a$keyw a$nw", $_);
	$sum[$count] += $n;
	$sum2[$count] += $n * $n;
	$key[$count] = $key;
    }
#    print "Records read: $count\n";
    close IN;
}

for ($i = 1; $i <= $#sum ; $i++) {
    $ave = $sum[$i] / $filecount;
    $sd = $sum2[$i]/$filecount - $ave*$ave;
    printf "%s%${nw}g\n", $key[$i], $opt_ave == 1 ? $ave : $opt_sd == 1 ? $sd : 9999.0;
}


sub process_arguments {
    # Process command line switches and leave file name arguments in ARGV. Also,
    # if no filename is specified, make a default setting from the passed parameter.

    local($default_argv0) = @_;
    local(@rest);
    local($var, $val);

    while (@ARGV) {
	$_ = shift(@ARGV);
	if (/^-(.+)/) {
	    $var = $1;
	    $_ = substr($_,1);
	    ($var,$val) = ($`,$') if /=/;
#	    print "var = $var  val = $val\n";
	    if ($flags =~ /:$var:/) {
		eval "\$opt_$var = 1;";
#		printf '%s scanned. $opt_%s = %d%s', $var, $var, eval "\$opt_$var", "\n";
	    }
	    elsif ($valued_options =~ /:$var:/) {
		if ($val eq "") {
		    $val = shift(@ARGV);
		}
		eval "\$opt_$var = \$val;";
#		printf '%s scanned. $opt_%s = %s%s', $var, $var, eval "\$opt_$var", "\n";
	    }
	    else {
		printf STDERR "Unrecognized option %s\n", $var;
		$errcnt += 1;
	    }
	}
	else {
	    push(@rest, $_);
	}
    }
    @ARGV = @rest;
    return $errcnt == 0;
}


