#!/usr/bin/perl

use Getopt::Std;

$debug = 0;


$cwidth = 10;

#
#  See usage for options explanation
#
getopts('PDdatqQxb');

if ( $#ARGV < 1 ) {
    usage();
    exit;
}

if ($opt_D) {
    $debug = 1;
}

if ($opt_x) {
    $opt_d = 1;
}

#
# Constants...
#
my $EQUATION_SPEC = '\%(\d+)([\+\-\/\*])\%(\d+)';


#
# get the list of statistics (converting to lower-case as we go)...
# and initialize the sums for each stat...
#
undef @stats;
undef @sum;
undef @num_vals;
do {
    $elt = lc shift;
    if ($elt ne "--") {
	if ($elt =~ /^(\d+)\:/) {
	    my $bin = $1;
	    $elt =~ s/^$bin\:/\{$bin\}/;
	}
        if ($elt =~ /^sum\:/) {
            # we're going to sum all bins
            $elt =~ s/^sum\:/\{\+\}/;
        }
        if ($elt =~ /^avg\:/) {
            # we're going to sum all bins
            $elt =~ s/^avg\:/\{a\}/;
        }

	print "stat = $elt\n" if $debug;

        @statistics = (@statistics, $elt);
    }
} while ($elt ne "--");

#
#  Print the header line
#
if ($opt_x) {
    if (!$opt_q and !$opt_Q) {
	print "Benchmark";
	foreach $stat (@statistics) {
	    chomp $stat;

	    if ($stat =~ /(\\*\%\d+[\+\-\/\*]\%\d+)\:(.+)/) {
		$p = $2;
		
		# for some reason, this actually changes the corresponding
		# value in @statistics
		$stat = $1;

		next if ($stat =~ /^~/);
	    }
	    elsif ($stat =~ /\%b/) {
		$p = "num_bins";
	    }
	    elsif ($stat =~ /\%f/) {
		$p = "file";
	    }
	    else {
		$p = $stat;
		next if ($stat =~ /^~/);
	    }
	    
	    print ",$p";
	}
	print "\n";
    }

    $delim = ",";
} else {
    if (!$opt_Q and !$opt_q) {
	print "#  Statistics ";

	foreach $s (@statistics) {
	    if ($s !~ /^~/) {
		my $stat = "";

		if ($s =~ /\%\d+[\+\-\/\*]\%\d+:(.+)/) {
		    $stat = $1;
		}
		elsif ($s =~ /\%b/) {
		    $stat = "num_bins";
		}
		elsif ($s =~ /\%f/) {
		    $stat = "file";
		}
		else {
		    $stat = $s
		}
		print "$stat ";
	    }
	}
	print "\n";
    }

    $delim = "";
}

$section = 0;
$num_dots = 23 + ($cwidth + 1) * ($#statistics + 1);


# Go through all the statistics...
while ($file_name = shift) {	#while file_name

    if (!$opt_d && $file_name =~ /\.[1a]\.out$/) {
	++$section;

	if ($section != 1) {
	    for (my $i=0; $i<$num_dots; ++$i) {
		print ".";
	    }
	    print "\n";
	}
    }


    #
    #  print the line header...
    #
    if (! $opt_Q) {
	if (!$opt_x) {
	    printf "%-22s:%s", $file_name, $delim;
	} else {
	    print $file_name;
	}
    }


    #
    #  Suck in the stats for this file into the "stats" namespace
    #  (whipe the namespace first)
    #
    undef @values;
    foreach $sym (keys %stats::) {
	undef $stats::{$sym};
    }

    read_stats($file_name, "stats");
    print "\nfinished reading statfile\n" if $debug;

    if ($debug>1) {
	foreach $sym (sort keys %stats::) {
	    local *val = $stats::{$sym};
	    print "$sym --> $val\n";
	}
    }


    #
    #  print the stats that we want...
    #
    foreach $stat ( @statistics ) {
	my $type = "std";

	#  handle non-printing stats...
	if ($stat =~ /^~(.+)/) {
	    $stat_name = $1;
	    $non_printing = 1;
	} else {
	    $stat_name = $stat;
	    $non_printing = 0;
	}

	print "examining statistic \"$stat_name\"\n" if $debug;
	#
	#  determine the "type" of stat we want here...
	#
	if ($stat_name =~ /(.+)::(.+)/) {
	    $type = "dist";
	    $dist_name = $1;
	    $dist_element = $2;

	    $dist_name =~ s/[\.\:\-]/_/g;
	    $dist_element =~ s/[\.\:\-]/_/g;
	}

	#  insert the file name...
	elsif ($stat_name =~ /\%f/) {
	    $type = "fname";
	    $vname = $type;
	}

	#  insert the number of bins
	elsif ($stat_name =~ /\%b/) {
	    $type = "nbins";
	    $vname = $type;
	}

	#  check for an equation
	elsif ($stat_name =~ /$EQUATION_SPEC/) {
	    $type = "equation";
	    $vname = $stat_name;
	}

	print "Suspect type is $type\n" if $debug;
	print "Stat name is $stat_name\n" if $debug;
	
	#
	#  build the variable name for this stat
	#
	if ($type eq "std") {
	  
	    # check for per-thread stat
	    if ($stat_name =~ /(.+)_(\d)$/) {
		$n = $1;
		$t = $2;
	      
		#	      $n =~ s/[\.\:\-]/_/g;
		$n =~ s/[\.\:]/_/g;
	      
		$vname = $n."[$t]";
	    } else {
		#	      $stat_name =~ s/[\.\:\-]/_/g;
		$stat_name =~ s/[\.\:]/_/g;
		$vname = $stat_name;
	    }
	} elsif ($type eq "dist") {
	  
	    if ($dist_name =~ /(.+)_(\d)$/) {
		$vname = $1."[$2]"."{$dist_element}";
	    } else {
		$vname = $dist_name."{$dist_element}";
	    }
	}
      
	print " -- looking for vname \"$vname\"  " if $debug;
      
	#
	#  Get the correct values to print from one of three sources:
	#    (1)  Directly from the stats database
	#    (2)  Expand the name from wildcards
	#    (3)  It may be an equation...
	#
	local *val = $stats::{$vname};
      
	if ($type eq "fname") {
	    undef $val;
	    $val = $file_name;
	}
	elsif ($type eq "nbins") {
	    undef $val;
	    $val = $num_bins;
	}
      
	if (($vname =~ /^\{\+\}/) and ($num_bins > 0)) {
	    undef $val;
	    $val = 0;
	    
	    print "Calculating SUM\n" if $debug;

	    for (my $b=0; $b<$num_bins; ++$b) {
		my $statname = $vname;
		$statname =~ s/\{\+\}/\{$b\}/;
		print "looking up statname $statname..." if $debug;
		local *v = $stats::{$statname};

		die "\nno val\n" if not defined $v;

		$val += $v;

		print "(adding $v to sum)\n" if $debug;
	    }
	}

	if (($vname =~ /^\{a\}/) and ($num_bins > 0)) {
	    undef $val;
	    $val = 0;
	    
	    print "Calculating AVERAGE\n" if $debug;

	    for (my $b=0; $b<$num_bins; ++$b) {
		my $statname = $vname;
		$statname =~ s/\{a\}/\{$b\}/;
		print "looking up statname $statname..." if $debug;
		local *v = $stats::{$statname};

		die "\nno val\n" if not defined $v;

		$val += $v;

		print "(adding $v to sum)\n" if $debug;
	    }

	    $val = $val / $num_bins;
	}

	if ($type eq "equation") {
	    undef $val;
	}

	if (defined $val) {
	    print "found!\n  pushing $val for $vname\n" if $debug;

	    if ($non_printing) {
		push @values, "~$val";
	    }
	    else {
		push @values, $val;
	    }
	} else {
	    #
	    #  this value was not found... it may use wildcards or
	    #  be a calculation...
	    #
	    my $nv;
	    if ($vname =~ /%/) {
		#
		#  Pass equations unchanged into the values list...
		#  (we evaluate them last)
		#
		if ($non_printing) {
		    $nv = "~$vname";
		}
		else {
		    $nv = $vname;
		}
	    } else {
		#
		#  check for wildcards
		#
		#   FIXME!
		$nv = "<<huh: $vname>>";
	    }
	    print "equation?\npushing $nv for $vname\n" if $debug;
	    push @values, $nv;
	}
    }

    $index = 0;
    $num_columns = $#values;
    foreach $v (@values) {	#foreach value

	if ($v =~ /^~(.+)/) {
	    $value = $1;
	    $printing = 0;
	}
	else {
	    $value = $v;
	    $printing = 1;
	}

	#
	#  Evaluate equations
	#
	if ($value =~ /%/) {
	    print "-- calculating \'$value\' using (@values) \n" if $debug;
	    $value = calc($value, @values);
	  
	    $values[$index] = $value;
	}

	#
	#  We have the column value now...
	#
	if (!$opt_x) {
	    print " ".pretty($value, $cwidth, $delim) if ($printing);
	} else {
	    #
	    # get rid of percentage-type values first
	    #
	    if ($value =~ /(.+)\%$/) {
		$value = $1 / 100;
	    }
	    print $delim.$value if ($printing);
	}

	#
	#  Calculate totals 
	#
	if (not $val =~ /--/) {
	    print "Adding $value for column $index\n" if $debug;
	  
	    $sum[$index] += $value;
	    $num_vals[$index]++;
	}
      
	++$index;
    }
  
    print "\n";
}

print "\n";


if ( $opt_t ) {

    printf "%-22s:%s", "Total", $delim  unless $opt_Q;

    for ($i=0; $i<=$num_columns; ++$i) {
	print " ".pretty($sum[$i], $cwidth, $delim);
    }
    print "\n";
}

if ( $opt_a ) {

    printf "%-22s:%s", "Average", $delim unless $opt_Q;

    for ($i=0; $i<=$num_columns; ++$i) {
	if ( $debug ) {
	    print "col: $i\n";
	    print "sum: $sum[$i]\n";
	    print "num_vals: $num_vals[$i]\n";
	}
	
	$avg = $sum[$i] / $num_vals[$i];
	
	print " ".pretty($avg, $cwidth, $delim);
    }
    print "\n";
}

exit;


sub usage {
    print "\nUsage:  get [-x][-q][-a] <stat> [<stat> ...] -- <file> [<file> ... ]\n";
    print "        <stat> = either the name of a statistic or an equation\n";
    print "                 Equations are made up of two column specifiers separated\n";
    print "                 by one of four operators [+,-,*,/]. A column specifier is\n";
    print "                 of the form \"%n\" where \'n\' is the column number.\n";
    print "                   Note 1: column specifiers must refer to a previous column.\n";
    print "                   Note 2: there should be no spaces in the equation unless\n";
    print "                           the entire equation is enclosed in quotes.\n";
    print "            -x = format output for Excel\n";
    print "            -q = don't print filename\n";
    print "            -Q = only print the values\n";
    print "            -b = dump bin / bin-index map\n";
    print "            -a = calculates the average value returned\n";
    print "\n";
    print <<EOF;
   Statistic specification syntax:
      Each stat specification my be either one statistic or an equation.

      Specifying statistics:
	-  A distribution is specified in the form \"<dist_name>::<element_name>\"
	-  Specify the sum of all bins for a stat using \"sum:<stat_name>\"

      Specifying equastions:
	- <column_spec><operator><column_spec>, where:
	    <column_spec> = \"\%<column_number>\"
	    <operator>    = \+\|\-\|\*\|\/

      General:
	-  Prefix the specification with a '~' to make a non-printing column. 
	   This is primarily used to provide data for an equation.
        -  Append a printable name to an equation by using \"\:<printed_name>\"
	-  A the file-name can be inserted into long stats lists by using the 
	   \"\%f\" token

      Binning Features:
	-  Specify a binned stat as \"<bin_number>:<stat_name>\"
	-  The number of bins can be inserted using the \"\%b\" token
        -  Return the sum of all bins by prefixing the stat with "sum:"
           instead of the bin number
        -  Return the average of all bins by prefixing the stat with "agv:" 
           instead of the bin number
EOF
}




#
# Read in the stats file.  Regular scalar statistics are read into the variable
# of the same name (e.g., $sim_cycle).  Scalar stats that end in _<digit> are
# assumed to be per-thread and are read into an array 
# (e.g., IPC_0 --> $IPC[0]).
#
# Distributions are read into hashes; if the name of the distribution ends in
# _<digit> an array of hashes is used.  The fetch_loss_counters dist is handled
# specially (since it's not a standard SimpleScalar distribution).
#
# Mapping from stat name to variable name:
#  - Periods, dashes, and colons are replaced with underscores
#  - per-thread stats (foo_0) are changed to foo[0]
#  - Names forced to lower-case
#
sub read_stats
{
    my $debug = 0;
    if ($opt_P) {
	print "\ndebugging parse\n";
	$debug = 1;
    }

    my $file = shift;
    my $pkg = shift;

    my $bin_number = 0;
    my $bin_hdr = "";

    #
    #  Constants (for matching)
    #
    my $STATS_HEADER = '- Begin Simulation Statistics -';
    my $BINNING_FLAG = 'PRINTING BINNED STATS';
    my $BINNING_HEADER = '---(.+?)\sBin---';   # minimal match
    my $BINNING_FOOTER = '---------------------';
    my $FOOTER       = '--  End Simulation Statistics  --';

    my $binning = 0;
    my $bin_number;

    print "Creating variables in package $pkg from file $file\n" if $debug;

    open(FILE, "<$file") or die "Can't open $file: $!";

    my $phase = 0;
    while (<FILE>) {

	#
	#  Read file until we find the stats header
	#
	if ($phase == 0) {
	    if (/$STATS_HEADER/) {
		$phase = 1;
	    }
	    next;
	}


	#
	#  Ignore any FLOSS counters we find...
	#
	if (/fetch_loss_counters_\d+.start/) {
	    do {
		$l = <FILE>;
	    } while ($l !~ /fetch_loss_counters_\d+.end/);
	    next;
	}


        #
        #  "normal" statistical value
        #
	my $stat;
	my $dist;
	my $val;
	my $subscript;
	
#	if (($stat, $val) = /^([\w\.\:]+)\s+(\d+\.?\d*\%*)\s+\#.*/) {
	if (($stat, $val) = /^([\w\.\:]+)\s+(\d+\.?\d*\%*)\s/) {

            # Replace periods with underscores
            $stat =~ s/\./_/g;
	    $stat =~ s/:/_/g;

            # If this is a per-thread stat (like blah_1)
            # change to blah[1]
            if ($stat =~ /_(\d)$/) {
                $subscript = $1;
                $stat =~ s/_\d$//;
            } else {
                undef $subscript;
            }

            #  replace any remaining dashes with underscore
            $stat =~ s/\-/_/g;

	    # force stat name to lower-case
	    $stat = lc $stat;

	    #
	    #  Magic happens here... create the stat name in the specified package
	    #                        and give it the value we grabbed earlier
	    #
            if (defined $subscript) {
 	        print "  -> $bin_hdr".$stat."[$subscript] = $val\n" if $debug;
                $ { $pkg . "::" .$bin_hdr . $stat . "[$subscript]" } = $val;
            } else {
 	        print "  -> $bin_hdr"."$stat = $val\n" if $debug;
                $ { $pkg . "::" . $bin_hdr . $stat } = $val;
            }
	}

        #
        #  If we are starting to read a distribution...
        #
	elsif (($dist) = /^([\w\.\:]+).start_dist/) {

            # Replace periods with underscores
            $dist =~ s/\./_/g;
	    $dist =~ s/:/_/g;

	    $dist = lc $dist;

            #  Handle per-thread distributions as an array of hashes
            if ($dist =~ /_(\d)$/) {
                $subscript = $1;
                $dist =~ s/_\d$//;
            } else {
                undef $subscript;
            }

	    while ($line = <FILE>) {
		last if $line =~/\.end_dist/;

                print "DIST: $line\n" if $debug;

		$line =~ /\s*([\w\/\(\)-]+(\s[\w\/]+)?)\s+([\-\d]+)/ or 
		  die "distribution entry format unknown";
                my $label = lc $1;
                my $value = lc $3;

                # replace dash with underscore
                $label =~ s/\-/_/g;
		$label =~ s/:/_/g;

                if (defined $subscript) {
                    print "  -> $bin_hdr"."$dist\[$subscript]{$label} = $value\n" 
		      if $debug;

                    $ { $pkg . "::" . $bin_hdr . $dist."[$subscript]{$label}" } = $value;
                } else {
                    print "  -> $bin_hdr"."$dist\{$label} = $value\n" if $debug;
                    $ { $pkg . "::" . $bin_hdr . $dist."{$label}" } = $value;
                }
	    }
        } elsif (/^fetch_loss_counters_(\d+).start/) {
	    $thread = $1;
	    while (<FILE>) {
		last if (/^fetch_loss_counters_(\d+).end/);
		
		my $label;
		my $idle;
		my $partial;
		my $part_num;

		($label, $idle, $partial, $part_num) = split;

                # replace dash with underscore
                $label =~ s/\-/_/g;

                if ($debug) {
                    print "  -> idle_cycles[$thread]{$label} = $idle\n";
                    print "  -> partial_cycles[$thread]{$label} = $partial\n";
                    print "  -> partial_num[$thread]{$label} = $part_num\n";
                }

                #  these are lists of hashes!
                $ {$pkg . "::idle_cycles"}[$thread]{$label} = $idle;
                $ {$pkg . "::partial_cycles"}[$thread]{$label} = $partial;
                $ {$pkg . "::partial_num"}[$thread]{$label} = $part_num;
	    }
	}
    }

    close(FILE);

    print "\n\nDone reading stat-file\n\n" if $debug;

    if (($bin_number > 0) and $opt_b) {
	print "Bin identification:\n";
	for($i=0; $i<$bin_number; ++$i) {
	    print "  bin $i = $bin_name[$i]\n";
	}
    }

    $num_bins = $bin_number;
}


sub pretty {
    my ($thing, $width, $delim) = @_;
    my $def_dec = 4;
    my $pct_flag = 0;

    my $debug = 0;

    if ($thing =~ /\%$/) {
	$def_dec = 3;
	$pct_flag = 1;

	chop $thing;		# we'll replace the % later...
    }

    if ($thing =~ /(\d+)\.\d+/) {
        $a = $1;

	$dec = $def_dec;	# default
	if ((length $a) > ($width-5)) {
	    $dec = $width - (length $a) - 1;
	}
	if ($dec < 0) {
	    $dec = 0;
	}

	if ($pct_flag) {
	    $fmt = "%".$width.".".$dec."f%%%s";
	} else {
	    $fmt = "%".$width.".".$dec."f%s";
	}
    } else {
	if ($pct_flag) {
	    $fmt = "%".$width."s%%%s";
	} else {
	    $fmt = "%".$width."s%s";
	}
    }

    print "pretty: pct: fmt=\'$fmt\', thing=\'$thing\', delim=\'$delim\'\n" if $debug;
    return sprintf "$fmt", $thing, $delim;
}


sub calc {
    my ($equation, @values) = @_;
    my $debug = 0;

    if ($debug) {
	print "calc(): equation = \'$equation\'\n";
	print "        values = @values\n";
    }
    
    if ($equation =~ /$EQUATION_SPEC/) {
	my $result;
	
	my @vals;

	$idx1 = $1;
	$op = $2;
	$idx2 = $3;

	
	$values[$idx1] =~ /^~*(.+)/;
	$first = $1;
	$values[$idx2] =~ /^~*(.+)/;
	$second = $1;

	if (($first =~ /%/) or ($second =~ /%/)) {
	    return "------";
	}
	
	$first = 0 if ($first =~ /--/);
	$second = 0 if ($second =~ /--/);
	
	print "it's an equation! ($first $op $second)\n" if $debug;
	
	if ($op eq "+") {
	    $result = $first + $second;
	} elsif ($op eq "-") {
	    $result = $first - $second;
	} elsif ($op eq "*") {
	    $result = $first * $second;
	} elsif ($op eq "/") {
	    if ($second == 0) {
		$result = "------";
	    } else {
		$result = $first / $second;
	    }
	}
	
	return $result;
    } else {
	# not a valid equation... just return
	return $equation;
    }
}
