#!/usr/bin/perl
use strict;

use PDL;
use PDL::Graphics::PGPLOT::Window;
#use PDL::Fit::Polynomial qw (fitpoly1d);
#use PDL::Slatec qw (polyfit polyvalue);
use PDL::Func;
use Text::CSV_XS;
use Data::Dumper qw (Dumper);

my @data;
if(@ARGV) {
    foreach my $file (@ARGV) {
	open (FILE, $file) || (warn("can't open \"$file\"; skipping"), next);
	my $d = process_file(\*FILE);
	$d->{'file'}=$file;
	close(FILE);
	push @data, $d;
    }
} else {
    my $d=&process_file(<STDIN>);
    $d->{'file'}="STDIN";
    push @data, $d;
}

foreach my $d (@data) {
    # &plotset($d, 1, 2, 3);
    &findfats($d);
}

exit(0);

sub process_file
{
    my $FILE = shift;
    my $csv = Text::CSV_XS->new({'binary'=>1});
    my $dataset;
    $dataset->{'date'} = $csv->getline($FILE);		# line 1
    $dataset->{'ecu'} = $csv->getline($FILE);		# line 2
    $csv->getline($FILE);				# line 3
    $dataset->{'groups'} = $csv->getline($FILE);	# line 4
    my $o1=$csv->getline($FILE);		# line 6
    my $o2=$csv->getline($FILE);		# line 7
    @{$dataset->{'objects'}}= map { $_ . ' ' . shift(@$o2) } @$o1;
    $dataset->{'units'} = $csv->getline($FILE);		# line 7
    # Data follows
    while ( !$FILE->eof() ) {
	my $line = $csv->getline($FILE);
	if (!defined $line) {
	    print "error: ".$csv->error_input()."\n";
	} else {
	    push @{$dataset->{'data'}}, $line;
	}
    }
    return $dataset;
}

sub plotset
{
    my ($data, $x, @ys)=@_;
    my $xlabel=$data->{'objects'}[$x];

    my $ary=pdl($data->{'data'});
    my $win=PDL::Graphics::PGPLOT::Window->new(Device => '/xs');
    my $i=0;
    foreach my $y (@ys) {
	if (!$i) {
	    $win->env ( min(slice($ary,$x)), max(slice($ary,$x)), min(slice($ary,$y)), max(slice($ary,$y)));
	}

	my $ylabel=$data->{'objects'}[$y];
        print "$y $ylabel\n";
	$win->label_axes($xlabel, $ylabel, $data->{'file'});

	$win->points(slice($ary,$x), slice($ary,$y));
	$i++;
    }
}

sub findfats
{
    my $data=shift;
    my @wot;
    my @runs;
    my $last=0;
    my $runnum=1;

    foreach my $row (@{$data->{'data'}}) {
        # print Dumper($row)."\n";
	next if($row->[4]!=100);
	if(scalar(@wot) && $row->[2] < $last) {
	    # print "pushing ", Dumper(@wot);
	    # push a copy, wot gets overwritten later
	    my @ary=@wot;
	    push @runs, \@ary;
	    undef @wot;
	}
	# printf("%f %f %f %f\n", $row->[1], $row->[2], $row->[3], $row->[4]);
	push @wot, $row;
	$last=$row->[2];
    }
    if(scalar(@wot)) {
	push @runs, \@wot;
    }

    # print Dumper(@runs);
    foreach my $set (@runs) {
	# print Dumper($set);
	my $start=$set->[0]->[2];
	my $end=$set->[-1]->[2];
	# printf("got %d -> %d\n", $start, $end);
	printf("%s : run #%d - ", $data->{'file'}, $runnum);
	$runnum++;
	if($start>4300) {
	    printf("start rpm %d is above 4300!\n", $start);
	    next;
	}
	if($end<6400) {
	    printf("end rpm %d is below 6400!\n", $end);
	    next;
	}
	#foreach my $row (@$set) {
	#   printf("%f %f %f %f\n", $row->[1], $row->[2], $row->[3], $row->[4]);
	#}
	my @ary=pdl(@$set);
	# print @ary;
	my $ydata=slice(@ary,'(1)');
	my $xdata=slice(@ary,'(2)');
	my $obj=PDL::Func->init(Interpolate => "Hermite", x=>$xdata, y=>$ydata);
	my $yi=$obj->interpolate(pdl(4200,6500));
	my $fats=slice($yi,'(1)')-slice($yi,'(0)');
	printf("%s seconds\n", $fats);
    }
}
