#!/usr/bin/perl -w

############################################################################
#  misc/floating-average
#
#  Part of the STXXL. See http://stxxl.sourceforge.net
#
#  Copyright (C) 2007 Johannes Singler <singler@ira.uka.de>
#  Copyright (C) 2010 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
#
#  Distributed under the Boost Software License, Version 1.0.
#  (See accompanying file LICENSE_1_0.txt or copy at
#  http://www.boost.org/LICENSE_1_0.txt)
############################################################################

# Calculate the floating average over $1 values in all columns
# Reading from stdin, writing to stdout
# Example: floating-average 3 <original >averaged

use strict;

my $span = $ARGV[0];
my @sums;
my @history;
my $count_sum = 1;
my $line_number = 0;
my $line;

while($line = <STDIN>)
{
  my @parts = split /\s+/, $line;

  my $c = 0;
  my $part;
  foreach $part(@parts)
  {
    if($part =~ /^[+-]?\d+\.?\d*([eE][+-]?\d+)?$/)
    { #is number
      if($count_sum == $span)
      {
        $sums[$c] -= $history[$line_number % $span][$c] || 0;
      }
      $history[$line_number % $span][$c] = $part;
      $sums[$c] += $history[$line_number % $span][$c];
      printf("%14.6f ", $sums[$c] / $count_sum);
      ++$c;
    }
    else
    {
      print(" $part ");
    }
  }
  print("\n");

  if($count_sum < $span)
  {
    ++$count_sum;
  }
  ++$line_number;
}
