#!/usr/bin/perl -w

# correlator.pl
# 4 March 2005
#
# Copyright 2005 by John R. Ackermann  N8UR (jra@febo.com)
# Licensed under the GPL version 2 or later; see the file COPYING
# included with this distribution.  I request, but do not require, that
# any modifications that correct bugs or errors, or increase the program's
# functionality, be sent via email to the author at the address above.

use strict;
use IO::File;
use Getopt::Std;
use n8ur qw(round lower_case);

my $opt;
my $data_file;
my $out_file;
my $df;
my $do;
my $i;
my $j;
my $reading;
my $x;
my $y1;
my $y2;
my $y3;
my @xarray;
my @y1array;
my @y2array;
my @y3array;
my @out1array;
my @out2array;
my $sum1;
my $sum2;
my $sum3;
my $average;
my $counter;
my @out3array;

#----------
# usage and option initialization
my $opt_string = 'ha:o:f:';
sub usage() {
print STDERR << "EOF";

usage: $0 [-h] -a samples -o output filename -f filename

-h	: this (help) message

-a	: number of samples to average by

-o	: output file name

-f	: data file name; if "-" read from STDIN

EOF
}

#----------------------
getopts( "$opt_string", \my %opt ) or usage() and exit;
usage() and exit if $opt{h};
usage() and exit if !$opt{f};
usage() and exit if !$opt{o};

$average = 10;
if ($opt{a}) {
	$average = $opt{a};
	}

if ($opt{f}) {
	$data_file = $opt{f};
	}
else {
	die "No data file specified!\n";
	}

if ($opt{o}) {
	$out_file = $opt{o};
	}
else {
	die "No output file specified!\n";
	}

###############################################################################
# main program
###############################################################################

# Add data points
$df = new IO::File $data_file, "r";
$do = new IO::File $out_file, "w";
if (defined $df) {
	while ($reading = <$df>) {
		if (substr($reading,0,1) =~ "[0-9]") {
			($x,$y1,$y2,$y3) = split(/\s/,$reading);
			push(@xarray,$x);
			push(@y1array,$y1);
			push(@y2array,$y2);
			push(@y3array,$y3);
		}
	}
} else {
	exit;
}

$counter = 0;
for ($j=0; $j<@xarray; $j++) {
	$sum1 += $y1array[$j];
	$sum2 += $y2array[$j];
	$sum3 += $y3array[$j];
	$counter++;
	if ($counter == $average) {
		printf $do "%s %5.4e %5.4e %5.4e\n",$xarray[$j],$sum1/$average,
			$sum2/$average,$sum3/$average;
		$sum1 = 0;
		$sum2 = 0;
		$sum3 = 0;
		$counter = 0;
		}
}
exit 0;

