#!/usr/bin/perl -w

use GD::Graph::lines;
#use POSIX;
use CGI qw/:standard:html2/;
use CGI::Carp qw/fatalsToBrowser/;

my $file = "/home/herbert/public_html/stats.txt";

my $lines = int($ENV{'QUERY_STRING'});

open (P, $file);
my @time;
my @temp;
$s=1;
while(<P>) {
  chomp;
  next unless (/^2008-(..)-(..)T(..):(..) (.*)/);
  my ($day,$mon)=($2,$1);
  $day++;
  if (($day>29 && $mon==2) || ($day>30 && ($mon==4||$mon==6||$mon==9||$mon==11))||($day>31)) { $day=1;$mon++;}
  push(@time, sprintf("%d.%d.", $day, $mon));
  my $temp=$5;
  $temp =~ tr/\.//d;
  push(@temp, $temp);
  push(@diff, $last-$temp);
  $s++ if (($last-$temp)>5000);
  push(@sold, $s);
  $last=$temp;
}

my @gdat;
push(@gdat, [@time]);
push(@gdat, [@temp]);
push(@gdat, [@diff]);
push(@gdat, [@sold]);

$elem = scalar @time;

$graph = GD::Graph::lines->new($elem* 1.7,768);
$graph->set_title_font("./Delicious-Heavy.ttf", 16);
$graph->set_legend_font("./Delicious-Bold.ttf", 14);
$graph->set_x_axis_font("./Delicious-Bold.ttf", 14);
$graph->set_y_axis_font("./Delicious-Bold.ttf", 14);
$graph->set_x_label_font("./Delicious-Bold.ttf", 14);
$graph->set_y_label_font("./Delicious-Bold.ttf", 14);

$graph->set_legend("Verkaufsrang (hoeher=schlechter)","Differenz zu Vorstunde","geschaetzte Verkaufszahl");

my $h = int($lines / 60);

$graph->set(
  x_label                 => "Tag",
  y1_label                 => "Verkaufsrang",
  y2_label                 => "Buecher verkauft",
  title                   => "Amazon-Verkaufsrang fuer PSTricks",
  x_tick_offset           => 13,
  x_label_skip            => 48,
  long_ticks              => 1,
  fgclr                   => "dgray",
  transparent             => 0,
  two_axes                => 1,
  line_width              => 2,
  use_axis                => [1,1,2],
  legendclr               => "dgray",
);

$graph->set_text_clr("dgray");


  my $gd;
  eval { $gd = plot_graph(\@gdat) };
  if ($@)
  {
      die $@ unless $@ =~ /size too small/;
      $gd = plot_graph(\gdat, %attribs, correct_width => 0);
  }

#print header("image/png");
print "Content-Type: image/png\n\n";

print $gd->png;


sub plot_graph
  {
      my $data    = shift;
      my %attribs = @_;
      my $graph   = GD::Graph::lines->new()
         or die GD::Graph->error;
      $graph->set(%attribs)     or die $graph->error;
      $graph->plot($data)       or die $graph->error;
  }
  
