#!/usr/bin/perl

$filespec = $ARGV[0];

open(LOG, $filespec) || die "Could not open [$filespec]\n";

open(DAT, "> trip.dat");

$prev_time = "";
$first_change = 1;

$temp = 0;

while($line = <LOG>) {

    if ($line =~ /^\[Sat Feb 14 ([0-9:]+) 2014\]\[RX\]O?K?41 ([ 0-9A-F]+)>?\[\/RX\]/) {
        $time = $1;
        $response = $2;
        $response =~ s/ $//;
        
 #       print "[$response]\n";

        @elm = split(/ /, $response);

        $pid = $elm[0];

        $a = hex($elm[1]);
        $b = hex($elm[2]);
        $c = hex($elm[3]);
        $d = hex($elm[4]);

        print "$time [$a][$b][$c][$d]\n";

        if ($time ne $prev_time) {
            $prev_time = $time;
            if (!$first_change) {
                print DAT "$time $load $rpm $speed $throttle $temp $intake_pressure $airflow_rate\n";
            }
            else {
                $first_change = 0;
            }
        }
        
        if ($pid eq "00") {
            print "capapilities\n";
        }
        elsif ($pid eq "01") {
            print "monitor status\n";
        }
        elsif ($pid eq "03") {
            $fuel_system_status = $a;  # bit encoded
        }
        elsif ($pid eq "04") {
#            print "engine load value: ";
            $load = sprintf("%.2f", (($a / 255.0) * 100.0));
#            print $load . "%\n";
        }
        elsif ($pid eq "05") {
 #           print "coolant temperature: ";
            $temp = $a - 40;
#            print ($a - 40) . "C\n";
        }
        elsif ($pid eq "0B") {
            $intake_pressure = $a;  # in kPa
        } 
        elsif ($pid eq "0C") {
#            print "engine RPM: ";
            $rpm = ($a * 256 + $b) / 4;
#            print $rpm . "\n";
        }
        elsif ($pid eq "0D") {
            $speed = $a;
            
#            print "vehicle speed: $speed\n";

#            if ($speed > 80) {
#                print ">>>>>> $time $speed\n";
#            }

            if ($load eq "") { $load = 0; }
            
        }
        elsif ($pid eq "10") {
            $airflow_rate = sprintf("%.2f", ($a * 256.0 + $b) / 100.0);  # in grams/sec
        }
        elsif ($pid eq "11") {
            $throttle = sprintf("%.2f", (($a / 255.0) * 100.0));
        }
        
#        for($i=0; $i < @elm; $i++) {
#            print $elm[$i] . " ";
#
#            
#        }
#       print "\n";

    }  # if returned data

}  # while

close DAT;


       
        
