#!/usr/bin/perl -w

# average.pl
# Read STDIN and output average of each X samples to STDOUT

# Copyright 2001 John Ackermann   Version: 15 July 2001
# May be freely used provided these notices are retained, and a copy
# of any modified version that's distributed to third persons is sent
# to jra@febo.com

use Getopt::Std;
use n8ur qw(round);

#----------
# display usage
my $opt_string = 'ha:';

sub usage() {
print STDERR << "EOF";

usage: $0 [-h] [-a samples to average]

-h	: this (help) message
-a	: samples to average; default 10
EOF
}
#----------

getopts( "$opt_string", \my %opt ) or usage() and exit;

# print usage
usage() and exit if $opt{h};

# set variables to command line params

my $samples = 10;
if ($opt{a}) {
        $samples = $opt{a};
        }

my $reading;
my $mjd;
my $value;
my $sum = 0;
my $counter = 0;

while ($reading=<STDIN>) {
	if (substr($reading,0,1) ne "#") {
		$counter++;
		($mjd,$value) = split(/\s/,$reading);
		$sum+=$value;
		if ($counter == $samples) {
			$result = $sum/$samples;
			printf "%s %12.12e\n",$mjd,$result;
			$counter = 0;
			$sum = 0;
		}
	}
}
