#!/usr/bin/perl -w
#---------------------------------------------------------------------------------------------------------
# showpics.pl - this lists the contents of a folder of photos as clickable links
#                    written by Eric Pence
#---------------------------------------------------------------------------------------------------------
use strict;
use CGI qw(-oldstyle_urls :standard);
use CGI::Carp qw(fatalsToBrowser);

# Define global variables
use vars qw($curr_dir $log_file);

#---------------------------------------------------------------------------------------------------------
# Grab the current directory from $0. The following regular expression
# looks for 'CURR_DIR\xxxxx.xxx' or 'CURR_DIR/xxxxx.xxx'. Place it in
# the BEGIN block so we can use it to include modules
#---------------------------------------------------------------------------------------------------------
BEGIN {
  $0 =~ '(.*[\\\/])\w+\.\w+$';
  $curr_dir = $1 || "./";

  # Set up error log file
  $log_file = "error_log.txt";
  use CGI::Carp qw(carpout);
  open(LOG, ">>${curr_dir}${log_file}")
        or die "Unable to append to error log: $!";
  carpout(*LOG);
}

use lib ( $curr_dir );
use FileHandle;

my $count = 0;
my $filename = '';
my $files = '';

# Get the list of the images to display
my @dir_contents = '';
my $work_dir = $curr_dir."../../mypics";

opendir(DIR,$work_dir) || die("Cannot open directory !\n");
@dir_contents = sort readdir(DIR);
closedir(DIR);

# Format the images as clickable links
foreach $filename (@dir_contents) {
if ($filename =~ /\.jpg/) {
    my $display_name = $filename;
    $display_name =~ s/\.jpg//;
    # Replace spaces with %20 for older browsers
    $filename =~ s/\s/%20/g;
    $files = "$files
        <li><a href=\"mypics/$filename\">$display_name</a></li>";
  }
}

print header();
print "<span style=\"{line-height: 1.50}\">
<ul>
$files
</ul>
</span>";