#!/usr/bin/perl

my (%temps,%kwhs);
my %tables;

while (<>)
  {
  chop;
  my ($key,
      $mode,$wmax,
      $s_tambient,$s_tbattery,$e_tambient,$e_tbattery,
      $s_soc,$e_soc,$soc,
      $s_kmi,$e_kmi,$kmi,
      $duration,
      $kwh) = split /,/,$_; 

  my $tslot = int($s_tbattery / 5)*5;
  my $kslot = int($wmax/1000)*1;
  $temps{$tslot}++;
  $kwhs{$kslot}++;
  my $key = "$tslot,$kslot";
  $tables{$key}{'samples'}++;
  $tables{$key}{'kmi'} += $kmi;
  $tables{$key}{'soc'} += $soc;
  $tables{$key}{'duration'} += $duration;
  $tables{$key}{'kwh'} += $kwh;
  }

print "NUMBER OF SAMPLES:\n";
print "kWh,Temp  ";
foreach (sort { $a <=> $b } keys %kwhs)
  {
  printf " %5d",$_;
  }
print " TOTAL\n";
foreach (sort { $a <=> $b } keys %temps)
  {
  my $temp = $_;
  printf "%5d     ",$temp;
  my $total = 0;
  foreach (sort { $a <=> $b } keys %kwhs)
    {
    my $kwh = $_;
    my $key = "$temp,$kwh";
    my $vals = $tables{$key}{'samples'}; $vals=0 if (!defined $vals);
    $total += $vals;
    printf " %5d",$vals;
    }
  printf " %5d\n",$total;
  }

print "\nKM(IDEAL)/MINUTE:\n";
print "kWh,Temp  ";
foreach (sort { $a <=> $b } keys %kwhs)
  {
  printf " %5d",$_;
  }
print "\n";
foreach (sort { $a <=> $b } keys %temps)
  {
  my $temp = $_;
  printf "%5d     ",$temp;
  my $total = 0;
  foreach (sort { $a <=> $b } keys %kwhs)
    {
    my $kwh = $_;
    my $key = "$temp,$kwh";
    my $kmi;
    if ((defined $tables{$key})&&($tables{$key}{'duration'}>0))
      {
      $kmi = $tables{$key}{'kmi'} / $tables{$key}{'duration'};
      }
    if (defined $kmi)
      {
      printf " %5.2f",$kmi;
      }
    else
      {
      print " -----";
      }
    }
  print "\n";
  }

print "\nEFFICIENCY:\n";
print "kWh,Temp  ";
foreach (sort { $a <=> $b } keys %kwhs)
  {
  printf " %5d",$_;
  }
print "\n";
foreach (sort { $a <=> $b } keys %temps)
  {
  my $temp = $_;
  printf "%5d     ",$temp;
  my $total = 0;
  foreach (sort { $a <=> $b } keys %kwhs)
    {
    my $kwh = $_;
    my $key = "$temp,$kwh";
    my ($soc,$kwh);
    if ((defined $tables{$key})&&($tables{$key}{'duration'}>0))
      {
      $soc = $tables{$key}{'soc'} / $tables{$key}{'duration'};
      $kwh = $tables{$key}{'kwh'} / $tables{$key}{'duration'};
      }
    if ((defined $soc)&&($kwh>0))
      {
      my $used = 53.0*($soc/100);
      printf " %5.1f",($used*100.0)/$kwh;
      }
    else
      {
      print " -----";
      }
    }
  print "\n";
  }
