#!/usr/bin/perl

close(STDERR);

use strict;
use CGI qw/:standard -debug/;
require 'timelocal.pl';



my $a = param('a');

my $datfile	= '/home/tosaka/.public_html.tosaka/rav4/fuel/fuel.txt';
my $efdatfile	= '/home/tosaka/.public_html.tosaka/rav4/fuel/ef.txt';

my $gnuplot	= "/usr/bin/gnuplot";
open(GNUPLOT, "| $gnuplot")	|| die;

print GNUPLOT "
	\!echo Content-Type: image/png
	\!echo
	set terminal png small
	set xdata time
	set timefmt \"\%Y\/\%m\/\%d\"
	set format x \"\%y\/\%m\"
	set xlabel \"Date\"
	\n";
#	set xrange ['1999/02/16':]

if($a eq "td")
{
    print GNUPLOT "
	set ylabel \"Km\"
	plot '$datfile' using 1:4 title \"Total Driving Distance\" \\
		with linespoints
	\n";
}
elsif($a eq "d")
{
    print GNUPLOT "
	set ylabel \"Km\"
	plot '$datfile' using 1:5 \\
		title \"Driving Distance Per Refueling\" with impulses
	\n";
}
elsif($a eq "qr")
{
    print GNUPLOT "
	set ylabel \"Litter\"
	plot '$datfile' using 1:2 title \"Quantity of Refueling\" \\
		with impulses
	\n";
}
elsif($a eq "pg")
{
    print GNUPLOT "
	set ylabel \"Yen/Litter\"
	plot '$datfile' using 1:3 title \"Price of Gas/Litter\" \\
		with linespoints
	\n";
}
#elsif($a eq "fe")
else
{
    open(DAT, $datfile)		|| die;
    open(EFDAT, "> $efdatfile")	|| die;
    while(<DAT>)
    {
	printf EFDAT "%s\t%lf\n", $1, $3/$2
	    if(/^(\S+)\s+(\S+)\s+\S+\s+\S+\s+([\d\.]+)\s*/);

    }
    close(EFDAT);
    close(DAT);

    print GNUPLOT "
	set ylabel \"Km/Litter\"
	plot '$efdatfile' using 1:2 title \"Fuel Efficiency\" \\
		with impulses
	\n";
}
close(GNUPLOT);
