#!/usr/bin/perl

if( $#ARGV ge 0) {
    $multiplier = $ARGV[0];
    print "using supplied multiplier $multiplier\n";
}
else{
    $multiplier = 1.0;
    print "using default multiplier of $multiplier\n";
}

# parse input file to extract time histogram values
%bins;
$nlines=0;
$valuesum=0;
while(<STDIN>){
    $nlines++;
    chomp;
    ($time_in,$value) = $_ =~ m/\s*(\d+)\s(\d+)\s*/;
    $bin_key = sprintf("%09d",$time_in);
    $bins{$bin_key} = $value;
    $valuesum += $value;
}

# sort keys, so that we can traverse them in reverse order
@keys_increasing = sort keys %bins;
$nkeys = scalar(@keys_increasing);
print "there are $nkeys keys\n";
print "total of all values is $valuesum\n";

# initializing the accumulators for this loop
$cumulative_weight = 0.0;
$accumulated_weighted_time = 0;
$final_accumlated_weight = 0.0;

# walks through histogram backwards, starting at the high-time end.  It weights each bin by the 
# command-line multiplier.  It accumulates a weighted time and a total weight until it reaches a 
# accumulated probability of 1.0.  

for($binindex=($nkeys-1);$binindex>=0;$binindex -= 1){
    $finalweight = ($bins{$keys_increasing[$binindex]})*$multiplier;
    $cumulative_weight += $finalweight;
#    print "index=$binindex  key=$keys_increasing[$binindex]  final weight = $finalweight  cumulative weight = $cumulative_weight";
    # once $cumulative_weight gets bigger than the accumulated number of trials in the original file
    # then we've accumulated 1.0 probability, so we stop updating the running integration
    if( int($cumulative_weight) < int($valuesum)){
	$time = int($keys_increasing[$binindex]);
	$floor_time = $time;
	$accumulated_weighted_time += ($time)*$finalweight;
	$final_accumulated_weight = $cumulative_weight;
    }
}

$final_averaged_time = $accumulated_weighted_time / $final_accumulated_weight;
print "all bins will be above $floor_time\n";
print "weighted time is $final_averaged_time\n";
