#!/usr/bin/perl -w

use strict;
use warnings;
use 5.010;
use Getopt::Long qw(GetOptions);
Getopt::Long::Configure qw(gnu_getopt);
use Data::Dumper;
use DateTime;
use Math::Round qw/nearest/;

my $srcFile = "/dev/stdin";
my $interval = 10;
my $precision = 1;

GetOptions(
	'interval|i=s' => \$interval,
	'precision|p=s' => \$precision,
) or die "Usage: $0 [--interval <sec:=10>][--precision <dec:=1>]\n";
my $pf = 1/(10**$precision);

die "No source file found!" unless (-e $srcFile);
my $srcHnd = undef;
open($srcHnd, "< :encoding(UTF-8)", $srcFile) || die "$0: can't open $srcFile for reading: $!";
my $limit = undef;
my $cnt = 0;
my $pe = 0;
my $a2 = 0;
my $a3 = 0;
my $a4 = 0;
my $a5 = 0;
my $te = 0;
while (<$srcHnd>) {
#
#	<Date>;<Time>;<Periode>;<A2>;<A3>;<A4>;<A5>;<Temperature>
#	[1-3]  [4-6]  [7]       [8]  [9]  [10] [11] [12]
#	3.10.2019;10:55:12;40804;318;311;103;103;39
#
	if (/^([0-9]+)\.([0-9]+)\.([0-9]+)[;\s+]([0-9]+):([0-9]+):([0-9]+);([0-9]+);([0-9\.]+);([0-9\.]+);([0-9\.]+);([0-9\.]+);([0-9\.]+)$/) {
		my $dt = DateTime->new(
    			year      => $3,
    			month     => $2,
    			day       => $1,
    			hour      => $4,
    			minute    => $5,
    			second    => $6,
    			time_zone => 'floating',
		);
#		print "$1.$2.$3 $4:$5:$6 => ".$dt->dmy('.')." ".$dt->hms."\n";
		if (!$limit) {
			$limit = $dt->clone();
			$limit->add( seconds => $interval );
			$cnt = 0;
			$pe = $7;
			$a2 = 0;
			$a3 = 0;
			$a4 = 0;
			$a5 = 0;
			$te = 0;
		}
#		print "Current: ".$dt->dmy('.')." ".$dt->hms."\n";
#		print "Limit:   ".$limit->dmy('.')." ".$limit->hms."\n";
#		exit 0;
		$cnt += 1;
		$a2 += $8;
		$a3 += $9;
		$a4 += $10;
		$a5 += $11;
		$te += $12;
		if ($dt >= $limit) {
#			print $limit->dmy('.').";".$limit->hms.";$pe;".nearest('0.1',$a2/$cnt).";".nearest('0.1',$a3/$cnt).";".nearest('0.1',$a4/$cnt).";".nearest('0.1',$a5/$cnt).";".nearest('0.1',$te/$cnt)."\n";
			print $limit->dmy('.')." ".$limit->hms.";$pe;".nearest($pf,$a2/$cnt).";".nearest($pf,$a3/$cnt).";".nearest($pf,$a4/$cnt).";".nearest($pf,$a5/$cnt).";".nearest($pf,$te/$cnt)."\n";
			undef $limit;
		}
	} else {
		print STDERR "ERROR: $_\n";
	}
}
