#!/usr/bin/perl
use strict;
#use lib '/usr/lib/perl5/5.8.3';
use CGI ':standard';
$CGI::POST_MAX=4;


my $picnum;
my $picbig;
my $picclean;
my $heading;
my $altext;
my $nextpic; my $nextindex;

my $i; my $j; my $k;	#loop index
my $photofield;	#single line from csv file
my @arrayline;		#split into an array
my @photoarray;	#array created from each line of csv file, as an array
my $datafile;		#name of csv file
my $fh;			#file handle
my $len1;		#refers to length of @photoarray
my @titles;  my @indexes; #list of required captions
my $title; my $index;

$photofield = "1";	#ensure variable is defined
$datafile = "../photos.csv";

open $fh, "$datafile" or die "Can't open photos.csv: $!";

#open data file and extract each line of data, plcing it in an array
$i = 0;

while (defined($photofield)) {
defined($photofield = readline($fh)) or last;
@photoarray = split(/,/,$photofield);
$indexes[$i]=$photoarray[0];
$titles[$i]=$photoarray[1];
$titles[$i]=~ s/\"//g;
$i++;
#print $photoarray[1]." ".$photoarray[3]." ".$photoarray[5]."\n";
}

$picnum=1;
$picnum=param('key');
$picnum =~ /(^\d{2}$)/;
if ($1 eq "") {
print "content-type: text/html\n\n";
print '<p>Action not permitted</p>';
die;
} else{
$picclean=$1;}

if (substr($picclean,0,1) eq "0"){
substr($picclean,0,1,"");
}

print "content-type: text/html\n\n";
#print "$picclean";

if ($picclean<=9) {
$picclean="0".$picclean;}

$picbig=$picclean.".jpg";
$nextindex=++$picclean;
#print "$nextindex $picbig ";

#reset $picclean to use as index for photo titles
--$picclean;

#if ($nextindex<10) {
#$nextindex="0".$nextindex;}
#print " $nextindex ";

$nextpic=$nextindex.".jpg";

#reuse nextpic to serve as target for pause/resume button
if (-e "../photos/$nextpic") {
$nextpic="upton_gal.cgi?&key=$nextindex";}
else{
$nextpic="newgal.cgi";}

#print "$nextpic";
#print " $picbig";

$heading="Upton Fen Gallery";
$altext="Pictures of Upton Fen";

print q(
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
);

print qq (
<title>$heading</title>);

print q(<STYLE>
@import url(../gallery.css);
</STYLE>);

print qq(

</head>
<body>);

print qq(
<div id="card">

  <div id="header">
  Upton Fen Gallery
  </div>
  <table id="images">
  <tbody id="image-body">
  <tr><td id="button-area">
  	
<div id="play_button">
  <a href="$nextpic"><img src="../resume-white.gif"></a>
  </div>
<div id="stop_button">
  <a href="new-upton-gal.cgi"><img src="../stop-button-white.gif"></a>
</div>
<div id="button">
  <a href="../index.html"><img src="../button-white.gif"></a>
</div>
  </td>
  <td>
<div id="image-area">  
  <img src="../photos/$picbig" alt="$altext">
</div>
  </td>
  </tr>
  <tr>
  <td>
  <div id="copyright">
  All photographs &copy; R A O'Neill 2003 - 2016
  </div>
  </td>
  <td>
  <div id="description">
  $titles[$picclean] 
  </div>
  </td>
  </tr>
  </tbody>
  </table>
  
  

  
</div>


</body>
</html>);