#!/usr/bin/perl
use strict;
use warnings;
use GD;
$| = 1;

# ------------Beginn Programmkonstante ---------------------
use constant Y_MAX      => 10;     # Maximalwert Y-Skala

# Bildabmessung (groesser als 60 x 60!)
use constant IMAGE_HEIGHT => 240;  # Bildgroesse in Y-Richtung
use constant IMAGE_WIDTH  => 400;  # Bildgroesse in X-Richtung
use constant MARKER       => 4;    # Tick-Laenge Skala

# Farben
use constant AREA_COLOR => (255, 0, 0);
use constant AXIS_COLOR => (0, 0, 0);
use constant TEXT_COLOR => (0, 0, 0);
use constant BG_COLOR   => (255, 255, 255);
# ------------Ende  Programmkonstante ---------------------

# Statt Datengenierierung durch ein Programm (auch extern)
# hier von Hand eingetragene Beispieldaten
# Ueberschrift
my $headline = "Netzwerk-Belastung";
# Datenarray
my @data = (5, 6, 4, 3, 2, 1, 4, 5 ,7);


# Hier geht's los
binmode STDOUT;
print "Pragma: no-cache\n";
print "Expires: Fri, 01 Jan 2010 01:00:00 GMT\n";
print "Content-type: image/gif\n\n";
print area_graph(\@data);


# Zeichnet den Grafen eines Wertearrays
sub area_graph # (\@data)
  {
  # Arrayreferenz uebernehmen
  my $data = shift;
  # Bild erzeugen
  my $image = new GD::Image(IMAGE_WIDTH, IMAGE_HEIGHT);
  # Farben definieren
  my $background = $image->colorAllocate(BG_COLOR);
  my $area_color = $image->colorAllocate(AREA_COLOR);
  my $axis_color = $image->colorAllocate(AXIS_COLOR);
  my $text_color = $image->colorAllocate(TEXT_COLOR);
  # Ursprung fuer Grafik innerhalb des Bildes festlegen
  my $X0 = 20;
  my $Y0 = IMAGE_HEIGHT - 20;
  my $graph_height = IMAGE_HEIGHT - 60;
  my $graph_width = IMAGE_WIDTH - 2*$X0;

  # Titel eintragen
  $image->string(gdLargeFont, 20, 12, $headline, $text_color);

  # Polygon der Daten erzeugen
  my $polygon = new GD::Polygon;
  $polygon->addPt( $X0, $Y0 );

  for (my $i = 0; $i < @$data; $i++)
    { $polygon->addPt($X0 + $graph_width/(@$data - 1) * $i,
                      $Y0 - $$data[$i]*$graph_height/Y_MAX); }
  $polygon->addPt($X0 + $graph_width, $Y0);

  # Polygon zeichnen
  $image->filledPolygon($polygon, $area_color);

  # X-Achse
  $image->line($X0, $Y0, $X0 + $graph_width, $Y0, $axis_color);
  for (my $x = 0; $x <= $graph_width; $x += $graph_width/(@$data - 1))
    { $image->line($x + $X0, $Y0 - MARKER, $x + $X0, $Y0 + MARKER,
                   $axis_color); }

  # Y-Achse
  $image->line($X0, $Y0, $X0, $Y0 - $graph_height, $axis_color);
  for (my $y = 0; $y <= $graph_height; $y += $graph_height/Y_MAX)
    { $image->line($X0 - MARKER, $Y0 - $y, $X0 + MARKER, $Y0 - $y,
                   $axis_color); }
  
  # Hintergrund transparent
  $image->transparent($background);
  # komplettes Bild zurückgeben
  return $image->gif;
  }