#!/usr/bin/perl

if ($ARGV[0] eq "-notext") {
  shift @ARGV;
  $notext=1;
} else {
  $notext=0;
}
foreach $file (@ARGV){
  open(MS, $file . ".htm") || die "Cant open infile $file" . ".htm $!";

  $psfile = (-e $file . ".prn") ? $file . ".prn": $file . ".ps";

  system("gs", "-q", "-r90", "-sDEVICE=ppmraw", 
	 "-sOutputFile=" . $file . ".%02d.ppm",
	 "-dNOPAUSE", $psfile, "quit.ps");
  open(OUT, '>' . $file . ".shtml") || 
      die "Cant open outfile $file" . ".shtml $!";

  select OUT;
  print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">';
  print '<HTML><HEAD><TITLE>', $file, '</TITLE></HEAD><BODY>', "\n";
  print '<!--#include virtual="/skel/header.shtml" -->', "\n";
  print "<H1>Luento: $file</H1>\n<HR>\n";
  printf 'Kalvot <A HREF="%s-x4.pdf">4 kappaletta</A> sivulla.', $file
      if -e $file . "-x4.pdf";
  printf 'Kalvot <A HREF="%s-x6.pdf">6 kappaletta</A> sivulla.', $file
      if -e $file . "-x6.pdf";
  print "<P><TABLE>\n";
  $count = 0;
  while(<MS>){
    s/<FONT[^>]*>//gi;
    s-</FONT>--gi;

    if (m/<H1>/){
      if ($count == 0){
	print "<TR><TD>";
	$count++;
      } else {
	$bytes += print_img($file, $count);
	print "<TR><TD>";
	$count++;
      }
    }
    print $_
	if (($count > 0) && ($notext == 0));
  }
  $bytes += print_img($file, $count);
  print "</TABLE>\n<HR>\n";
  print '<!--#include virtual="/skel/footer.shtml" -->', "\n";
  print "</BODY></HTML>\n";
  close OUT;
  printf STDOUT "Kuvat: %d tavua, %f kiloa, %f megaa\n", $bytes, $bytes/1024, $bytes/(1024 * 1024);
  $bytes += (stat $file . ".shtml")[7];
  printf  STDOUT  "Yhteensä: %d tavua, %f kiloa, %f megaa\n", $bytes, $bytes/1024, $bytes/(1024 * 1024);
  system ("ln", "-s", $file . ".shtml", "index.shtml");
}  

sub print_img {
  local ($file, $count) = @_;
  local ($ppm, $thumb, $img, $_);
  $ppm = sprintf("%s.%02d.ppm", $file, $count);
  $thumb = sprintf("t-%s.%02d.gif", $file, $count);
  $img = sprintf("%s.%02d.gif", $file, $count);
  print STDOUT $ppm, "=> ", $img, "\n";
  system(sprintf("pnmflip -r270 %s | ppmtogif > %s",
		 $ppm, $img));
  print STDOUT "\t=> ", $thumb, "\n";
  system(sprintf("pnmscale 0.25 %s | ppmquant 16 | pnmflip -r270 | ppmtogif > %s",
		 $ppm, $thumb));
  
  unlink $ppm;
  print "</TD><TD>\n" if ($notext == 0);
  $width = -1; $height = -1;
  if (open(INFO, sprintf("file %s|", $thumb))) {
    while(<INFO>) {
      if (m/GIF.*\D(\d+) x (\d+)/) {
	$width = $1; $height = $2;
      }
    }
    close INFO;
  }
  die "GEE not size" if ($width < 0 || $height < 0);
  printf '<A HREF="%s"><IMG SRC="%s" ALT="kuva %d" width=%d height=%d></A>',
  $img, $thumb, $count, $width, $height;
  print "</TD></TR>\n";

  return (stat ($thumb))[7];
}
