#!/usr/bin/perl -w

use strict;
use warnings;

# Author : Nathael Pajani
# Copyright 2016 Nathael Pajani <nathael.pajani@techno-innov.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# How to use this script/programm
# FIXME : TODO.

use GD::Graph::bars;


my $debug = 1; # 0: no debug

my $file = $ARGV[0];
if (! -e $file) {
	print "Need file name as first argument\n";
	exit 1;
}

my $count = 0;
my @stime;
my @stempdata;
my @scapdata;
my @sresdata;

open(LOGFILE, "<", $file);
foreach my $line (<LOGFILE>) {
	chomp($line); # remove the newline from $line.
	my $w = "(.+?)";
	if ($line =~ m/Temp read: $w - raw/) {
		push(@stime, $count);
		push(@stempdata, $1);
		# Increment counter
		$count++;
	} elsif ($line =~ m/ADC9: $w, ADC10: $w/) {
		push(@scapdata, $1);
		push(@sresdata, $2);
	}
}


print "Got ".$#stime." values\n";

# Temperature
my $tempgraph = GD::Graph::bars->new(($#stime*2), 800);
$tempgraph->set( 
             x_label => 'time',
             y_label => 'temp',
             title   => 'Temp sensor vs time',
             transparent => 0
) or warn $tempgraph->error;
my @tempdata = (\@stime, \@stempdata);
my $temp_gd = $tempgraph->plot(\@tempdata) or die $tempgraph->error();
# Save graph
open(IMG, '>filetemp.png') or die $!;
binmode IMG;
print IMG $temp_gd->png;
close(IMG);

# Capacitance
my $capgraph = GD::Graph::bars->new(($#stime*2), 800);
$capgraph->set( 
             x_label => 'time',
             y_label => 'cap',
             title   => 'Temp sensor vs time',
             transparent => 0
) or warn $capgraph->error;
my @capdata = (\@stime, \@scapdata);
my $cap_gd = $capgraph->plot(\@capdata) or die $capgraph->error();
# Save graph
open(IMG, '>filecap.png') or die $!;
binmode IMG;
print IMG $cap_gd->png;
close(IMG);

# Resistivity
my $resgraph = GD::Graph::bars->new(($#stime*2), 800);
$resgraph->set( 
             x_label => 'time',
             y_label => 'res',
             title   => 'Temp sensor vs time',
             transparent => 0
) or warn $resgraph->error;
my @resdata = (\@stime, \@sresdata);
my $res_gd = $resgraph->plot(\@resdata) or die $resgraph->error();
# Save graph
open(IMG, '>fileres.png') or die $!;
binmode IMG;
print IMG $res_gd->png;
close(IMG);

