#!/usr/bin/perl
use warnings;
use strict;
use Image::Magick;

$| = 1;

#------------------ Konfiguration ------------------
# Anzahl Spalten
my $colspan = 6;

# Groesse des Vorschaubildes
my $maxsize = 120;

#my $CGI = 1;  # Ausgabe als CGI-Programm
my $CGI = 0;  # Ausgabe in Datei

# Pfad zu den Bildern innerhalb "Document Root"
# Achtung: '/' am Ende noetig!
# wird bei $CGI = 0 ignoriert (Bilder im akt. Dir).
my $imgpath = '/bilder/';

#------------------ Konfiguration ------------------

my @files = ();
my $query = Image::Magick->new();
# Dateinamen einlesen

while(<*>)
  { push @files, $_ unless /^\./; }

if ($CGI)
  {
  # Ausgabe als CGI-Programm
  my $path = $ENV{'DOCUMENT_ROOT'} . $imgpath;
  chdir($path) or die "Can't chdir $path: $!\n";
  $file = '>&STDOUT';
  print "Content-type: text/html\n\n";
  }
else
  {
  # Ausgabe in Datei:
  $file = '>catalog.html';
  }
open(OUT, $file) or die "Oops: $!";

print OUT qq~
<html>
<head><title>Bilderkatalog</title></head>
<body>
<h3>Bilderkatalog</h3>
<p>
<table border="0" cellpadding="2" cellspacing="0" align="center">
<tr>
~;

my $col = 0;
for my $file (sort alphabetically @files)
  {
  $col++;
  if ($col > $colspan)
    {
    $col = 1;
    print OUT "</tr><tr>\n";
    }

  my ($width, $height, $size, $format) = $query->Ping($file);
  unless ($width && $height)
    {
    warn "Bad file $file";
    next;
    }
  my $psize = "($width x $height)";
  if(($width > $maxsize) || ($height > $maxsize))
    {
    my $scale;
    if ($width > $height)
      { $scale = $maxsize/$width; }
    else
      { $scale = $maxsize/$height; }
    $width  = int($width * $scale);
    $height = int($height * $scale);
    }
  print OUT qq~
   <td width="132">
   <a href="$file"><img src="$file" alt="$file" width="$width" height="$height"></a>
   <br /><a href="$file">$file</a><br />$psize
   </td>
   ~;
  }

print OUT qq~
</tr></table></p>
</body>
</html>
~;

sub alphabetically
  {
  my ($aa, $bb) = ($a, $b);
  $aa =~ tr/A-Z/a-z/;
  $bb =~ tr/A-Z/a-z/;
  return $aa cmp $bb;
  }