#!/usr/bin/perl
#
# input: a bunch of numbers on cmd line
# output: an average (mean), sample standard deviation, sample standard deviation percent, and which input was closest to the avgerage
#

my $sum = 0;
my $count = @ARGV;
if ($count == 1) {
	printf "%.4f %.4f %.4f %d\n", $ARGV[0], 0, 0, 1;
} elsif ($count == 0) {
	printf "%.4f %.4f %.4f %d\n", $ARGV[0], 0, 0, 0;
} else {
	foreach $val (@ARGV) {
		$sum += $val;
	}
	$avg = $sum / $count;
	
	$index = 1;
	foreach $val (@ARGV) {
		$sqdiff = ($avg - $val)**2;
	
		# keep track of the value which has the least difference from the average
		if (!defined $closest_index) {
			$mindiff = $sqdiff;
			$closest_index = $index;
		}
		elsif ( $sqdiff < $mindiff ) {
			$mindiff = $sqdiff;
			$closest_index = $index;
		}
		$totalsqdiff += $sqdiff;
		$index++;
	}
	my $stddev = ($totalsqdiff / ($#ARGV)) ** 0.5;
	# if $stddev is 0 and the avgerage is 0, then return 0 for $stddevpct (do not divide by zero below)
	if (($stddev == 0) && ($avg == 0)) {
			$stddevpct = 0;
	} else {
		$stddevpct = 100 * $stddev / $avg;
	}
	printf "%.4f %.4f %.4f %d\n", $avg, $stddev, $stddevpct, $closest_index;
}
