#!/usr/local/bin/perl
use CGI qw(:standard);
use File::stat;
use Time::localtime;
use strict;

my $url = "http://www.moritorium.com/blackout/get_comic.cgi";

sub make_controls
{
  # for a given comic index and string, generate appropiate HTML
  my $name = shift;
  my $index = shift;
  if(defined $index) {
    return " <a href=\"$url?comic=$index\">$name</a> ";
  } else {
    return " $name ";
  }
}

#look for the first string of digits in the file and use that for comparison
sub compare_files
{
  $a =~ m/(\d+)/;
  my $a_number = $1;
  $b =~ m/(\d+)/;
  my $b_number = $1;
  return $a_number <=> $b_number;
}

my @files = glob('page*.jpg');
@files = sort compare_files @files;
my $first_index = 1;
my $last_index = @files; #length of files
my $previous_index = $last_index - 1;
my $next_index = undef;

# find the next and previous comic index for the given input
my $current_comic = param('comic');
if($current_comic and $current_comic < $last_index) {
  if($current_comic > 1) {
    $previous_index = $current_comic - 1;
  } else {
    $previous_index = undef;
  }
  $next_index = $current_comic + 1;
}

my @controls = (make_controls("FIRST", $first_index),
               make_controls("PREVIOUS", $previous_index),
  	       make_controls("NEXT", $next_index),
  	       make_controls("LAST", $last_index));

my $filename = @files[$current_comic - 1];
my $controls = join("\n", @controls) . "\n";
my $date_string = ctime(stat($filename)->mtime);
print <<END;
Content-type: text/html

<html>
<head><title>BLACKOUT</title></head>
<body TEXT="#ffffff" BGCOLOR="#000000">
<p ALIGN="CENTER"><img src="$filename"></p>
<p ALIGN="CENTER">$controls</p>
<p ALIGN="CENTER"><A HREF="http://www.moritorium.com/blackout/hakiped.html">Glossary & Reference Guide</a></p>
<p ALIGN="CENTER"><A HREF="http://moritorium.com/blackout/dossier/charguid.html">Character Guide</a></p>
<p ALIGN="CENTER">BLACKOUT $current_comic of $last_index: updated $date_string</p>

</body>
</html>
END
