#!/usr/bin/perl

my $debug = 0;

close(STDERR);

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

my $a = param('a');;

if($debug)
{
    $a = 'fe'
	if($a eq '');
}


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

my $gnuplot	= "/usr/bin/gnuplot";
open(GNUPLOT, "| $gnuplot")	or 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)		or die;
    open(EFDAT, "> $efdatfile")	or 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);
