#!/usr/bin/perl
# Animation
#
#  input: a list of images
#  output: the page for image i

use CGI;

# Get CGI parameters.
my $query = new CGI;
my $this = $query->param('this');
my $nSeconds = $query->param ('secs');
my $play = $query->param ('play');
my $stop = $query->param ('stop');

my $scriptName = $ENV{SCRIPT_NAME}; 

# Go immediately to next image if user hits "play" button.
$this++ if ($play);

# Read list of images.
my $buf;
&ReadFile ("images.lst", \$buf);
my @images = split (/\n/, $buf);

# Extract the one we need.
my ($thisImgsrc, $thisText) = split (/\t/, $images[$this]);

# Calculate previous and next image, wrapping at the ends. 
my $prev = $this > 0 ? $this-1 : $#images;
my $next = $this < $#images ? $this+1 : 0;
my $prevPage = "$scriptName?this=$prev";
my $nextPage = "$scriptName?this=$next";

# Select options for user control of animation interval.
my @times = (10,30,60);
my $time;
my $timeSelect = '';
for $time (@times) {
  $timeSelect .= "<option";
  $timeSelect .= " selected" if ($time == $nSeconds);
  $timeSelect .= ">$time</option>\n";
}

# Animation only happens when the param "secs" is defined.
my $meta =  $nSeconds && (!$stop) 
   ? "<META HTTP-EQUIV=REFRESH CONTENT=\"$nSeconds; url=$nextPage&secs=$nSeconds\">" 
   : '';

# Read template.
my $template;
&ReadFile ("template.htm", \$template);

# Merge this slide's data into the template.
$template =~ s/<%(.*?)%>/eval($1)/gse;

print "Content-type: text/html\n\n";
print $template;

sub ReadFile
{
  my ($fname, $buf) = @_;
  if (open (INPUT, $fname)) {
    my $oldSeparator = undef $/;
    $$buf = <INPUT>;
    $/ = $oldSeparator;
    close INPUT;
  }
}