#!/usr/bin/perl
#
# simple binning of two columns in a datafile
#
# usage: boxcar.pl  bin_width
#
# MWR 8/22/2002

$debug = 0;


$width = $ARGV[0];
if ($debug > 0) {
  printf "bin width is %d bins \n", $width;
}

$bins_filled = 0;

while (<STDIN>) {

  $line = " " . $_;
  @words = split(/\s+/, $line);
  if ($#words < 2) {
    if ($debug > 0) {
      printf "bad line ... skipping \n";
    }
    next;
  }

  $x1 = $words[1];
  $x2 = $words[2];
  if ($debug > 0) {
    printf "  x1 %s   x2 %s \n", $x1, $x2;
  }
  
  # we skip data until we can fill bins
  if ($bins_filled < $width) {
    $array1[$bins_filled] = $x1;
    $array2[$bins_filled] = $x2;
    $bins_filled++;
    next;
  }

  # okay, now we calculate and spit out binned value based on current
  #   values in arrays
  $sum1 = 0;
  $sum2 = 0;
  for ($i = 0; $i < $width; $i++) {
    $sum1 += $array1[$i];
    $sum2 += $array2[$i];
  }
  $avg1 = $sum1/$width;
  $avg2 = $sum2/$width;
  printf "%10.5f %10.5f \n", $avg1, $avg2;

  for ($i = 0; $i < $width; $i++) {
    $array1[$i] = 0;
    $array2[$i] = 0;
  }
  $bins_filled = 0;
  $array1[$bins_filled] = $x1;
  $array2[$bins_filled] = $x2;
  $bins_filled++;

}




exit 0;
