#!/usr/bin/perl -w
#-------------------------------------------------------------------------------
# viewbooks.pl - this lists the books I have on my Droid from a file
# written by Eric Pence
#-------------------------------------------------------------------------------
use strict;
use CGI qw(-oldstyle_urls :standard);
use CGI::Carp qw(fatalsToBrowser);
use Data::Dumper;
use IO::File;
use File::stat;
use Date::Format;

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

$| = 1; # Disable buffering

my $count = 0;
my $books = '<ul>';

# Get the stored book list from the file
my $file = IO::File->new("ebooks.txt", 'r') || die "Cannot open file: $!";
while(<$file>) {
my $name = clean_up($_);
$books .= "<li><span style='color:#333399' title=\"$name\">$name</span></li>";
$count++;
}
$file->close;
$books .= '</ul>';

# Get last-modified date of file
my %months = (
Jan => 'January',
Feb => 'February',
Mar => 'March',
Apr => 'April',
May => 'May',
Jun => 'June',
Jul => 'July',
Aug => 'August',
Sep => 'September',
Oct => 'October',
Nov => 'November',
Dec => 'December',
);
my $fileDate = ctime(stat("ebooks.txt")->mtime);
my $colon1 = index $fileDate,':';
my $colon2 = rindex $fileDate,':';
my $len = length $fileDate;
my $mth = substr($fileDate,4,3);
my $month = $months{$mth};
my $changeDate = $month.substr($fileDate,7,$len-$colon1-9).','.substr($fileDate,$colon2+3);

print header();
print "<table>
<tr>
<td width=\"10\"></td>
<td>
$books
</td>
</tr>
<tr>
<td></td><td><p>$count books - list updated $changeDate</p></td>
</tr>
</table>";

exit;

#-------------------------------------------------------------------------------
# Replace certain characters to make browser compliant
#-------------------------------------------------------------------------------
sub clean_up {
my ($str) = @_;
$str =~ s/\s&\s/ &amp; /g;
$str =~ s/'/\'/g;
$str =~ s/\//&frasl;/g;
$str =~ s/ _ / \/ /g;
return $str;
}