#!/usr/bin/perl
# fotohtml.pl -- Perl version of Fotohtml
# J C Nash (C) 1991-2025
# version 2019-2-11 -- added Dutch ?? what
# 
## ?? watch for use of : after filename. Colon NOT allowed in filenames
use strict;
use Cwd;
use Cwd 'realpath';
use File::Copy;
use File::Spec;
use File::Find;  # module that lets us build a full tree.
use File::Basename; # module that parses filenames into path, name, extension etc.
use File::stat; # module to allow access to file characteristics by name
use File::Compare; # module to compare 


my ($fcount, $filedone, $fword, $ii, $jj, $kk, $ifn);
my ($havefile, $hsave, $hstring, $inpath, $fextn, $fnroot, $framnum, $hhname);
my ($keepon, $nfoto, $oldtext, $tfnam, $tline, $tpath, $spath);
my ($mfn, $response, $mcount, $numfiles);
my (@imfiles, @dirnotlist, @listnotdir, @tfiles, @inlines);
my ($title, $header, $numlines, $aline);
my (@capfiles, @captions, $cfile, $ccap, $numcaps);


my $fperpage=10; # ?? eventually put this in command line

print "fotohtml -- (C) J C Nash 1991-2025\n";
print "\n";
my $numclargs = @ARGV; # get the number of arguments on the command line
if ($numclargs==0) { #if no command line parameters, then display a message about the program
   print "This program was written by John C. Nash\n";
   print "     18 Spyglass Ridge, Ottawa, Ontario, K1S 1R6\n";
   print "       nashjc\@ncf.ca\n";
   print "\n";
   print "Usage:\n";
   print "     fotohtml myfile\n";
   print "creates HTML version of photo lists from file myfile.txt\n";
   print "  to the file myfile.htm\n";
   print "This version puts a maximum of ",$fperpage," images in each HTML file\n";
   print "with a 'NEXT' button on the HTML page.\n";
   print "\n";
   print "Root for file name of source text =";
   $ifn = <>;
   chomp($ifn); # 110307 fix
} else { 
   $ifn = $ARGV[0]; # filename root is first parameter
}
print "working with input filename = $ifn\n";
# Assume you can put a path in front of the filename, and all work takes place there 
# ?? THIS MAY BE A BAD IDEA!! But we'll get things running first simply.

# ?? deblank(ifn); ??needed
$ifn=realpath($ifn); # expand to full path 
($fnroot,$inpath,$fextn) = fileparse($ifn);
if ( ! $fextn ) { $fextn='.txt'; }

$fnroot=~s/$fextn$//;

print "full input filename = $ifn\n";
print "filename root = $fnroot\n";
print "filename extension is $fextn\n";
print "path is $inpath\n";

#print "inpath=$inpath\n";
#my $tmp=File::Spec->rel2abs($inpath); #NOTE: abs_path and realpath functions don't seem to work correctly!!
#print "tmp = $tmp\n";
#my $rpath=realpath($ifn);
#print "realpath(ifn) = $rpath\n";
#$rpath=realpath($inpath);
#print "realpath(inpath) = $rpath\n";

chdir($inpath);
#$tpath=getcwd;
#print "Path should now be $tmp =?= $tpath\n";

$mfn='missing.txt';
if (-e $mfn) { 
   print "missing.txt EXISTS -- Overwrite ([cr]=N):";
   $response = <STDIN>;
   if ( !(($response eq 'Y') || !($response eq 'y'))) {
        print "Stopping -- do not want to overwrite file\n";
        die("Done this run");
   }
}
open (MFILE, ">$mfn"); # open for writing at the beginning
$mcount=0;
if (!(-e $ifn)) {
   die("ERROR -- file $ifn does not exist");
}
open (INFILE, $ifn);
print "File : $ifn OPEN FOR INPUT\n";
@inlines=<INFILE>;
close(INFILE); # no need to keep it open
$numlines=@inlines;
print "$numlines lines read\n";


# Now get file names of image files
print "Image files\n";
@dirnotlist=();
@listnotdir=();
@imfiles=();
@tfiles=glob("*.GIF");
$numfiles=@tfiles;
print "$numfiles of type .GIF\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.gif");
$numfiles=@tfiles;
print "$numfiles of type .gif\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.JPG");
$numfiles=@tfiles;
print "$numfiles of type .JPG\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.jpg");
$numfiles=@tfiles;
print "$numfiles of type .jpg\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.JPEG");
$numfiles=@tfiles;
print "$numfiles of type .JPEG\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.jpeg");
$numfiles=@tfiles;
print "$numfiles of type .jpeg\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.PNG");
$numfiles=@tfiles;
print "$numfiles of type .PNG\n";
@imfiles=(@imfiles,@tfiles);
@tfiles=glob("*.png");
$numfiles=@tfiles;
print "$numfiles of type .png\n";
@imfiles=(@imfiles,@tfiles);
$numfiles=@imfiles;
print "$numfiles total image files\n";	

# sort the files

@tfiles = sort @imfiles;
@imfiles = @tfiles; 

# Now parse out the captions file
$kk=0; # count lines
my $cfcount=0; # count files listed in captions
# Get first non-null line as title 
$header=''; # initialize to nothing
while (!$header && $numlines) {
   # print "Header = |$header| and numlines=$numlines\n";
   $aline=shift(@inlines);
   $numlines--;
   $kk++;
#   print "$kk:$aline\n";
   $aline=trim($aline);
   if ($aline) { # non blank 
	$header=$aline;
        # Do NOT allow comment before header
   }
} # end loop until title found
print "Header=$header\n";
if (! $numlines) {
   die("File has no non-blank lines");
}
# Process rest of file
$cfile=''; # start with no fle
$ccap=''; # just in case
$numcaps=0;
while ($numlines) {
   $aline=shift(@inlines);
   $numlines--;
   $kk++;
#   print "$kk:$aline\n";
   if (substr($aline,0,1) eq '*') { # commentary
     # do nothing
   } else {
      if (! $cfile) { # do not have filename
         if (trim($aline)) { # we have a non-null line, so extract
            $jj=index($aline," "); # find first space
            $cfile=substr($aline,0,$jj);
            $ccap=substr($aline,$jj+1); 
#            print "Found filename=$cfile\n";
         } else { #no file and null line -- ignore
         }
      } else { # have a filename -- check for more caption
         if (trim($aline)) {
# ??? should we chomp() first??
            $ccap=$ccap." ".$aline; 
         } else { # null line, so move on
#            print "cfile=$cfile; caption=$ccap\n";
            $numcaps++;
            push(@captions, $ccap);
            push(@capfiles, $cfile);
            $cfile=''; # null the filename
            $ccap=''; # just in case
         }
      }
   } # end non-commentary
} # end loop over lines

# process lists and prepare "missing" file -- Compare and report
  print "$numfiles Image files in directory\n";
  print "$numcaps Image files in caption file\n";

#  @tfiles=sort @capfiles; # sort temporarily for checking

# ??? NOTE -- if we have sorted, the following can be improved in efficiency

  @dirnotlist = (); # null the list of files in directory and not in list
  $kk=0; # counter
  for ($ii=0; $ii<$numfiles; $ii++) { # loop over the directory files
    my $dfile = $imfiles[$ii];
    my $match=0;
    for ($jj=0; $jj<$numcaps; $jj++) { # loop over the captions files
       if (uc($dfile) eq uc($capfiles[$jj]) ) { # match
          # print "Directory MATCH: $dfile\n";
          $capfiles[$jj]=$dfile; # ensure we can find the file if case sensitive OS
          $match=1;
       }
    } # end loop on captions
    if (! $match) {
       $kk++; # count file not found
       print "$kk, $dfile NOT found in captions\n";
       push(@dirnotlist,$dfile);
    }
  } # end loop on dirfiles    
  my $numdirnotlist=$kk;
  @listnotdir = (); # null the list of files in captions but not in dir
  $kk=0; # counter
  for ($ii=0; $ii<$numcaps; $ii++) { # loop over the captions files
    my $dfile = $capfiles[$ii];
    my $match = 0;
    for ($jj=0; $jj<$numfiles; $jj++) { # loop over the directory files
       if (uc($dfile) eq uc($imfiles[$jj]) ) { # match
          # print "Captions MATCH: $dfile\n";
          $match=1;
       }
    } # end loop on imfiles
    if (! $match) {
      $kk++; # count file not found
      print "$kk, $dfile NOT found in directory\n";
      push(@listnotdir,$dfile);
    }
  } # end loop on dirfiles    
  my $numlistnotdir=$kk;
  print "Total of $numdirnotlist files in directory not in captions\n";
  print MFILE "Total of $numdirnotlist files in directory not in captions\n";
  for ($ii=0; $ii<$numdirnotlist; $ii++) {
      print MFILE "$dirnotlist[$ii]\n";
  }
  print "Total of $numlistnotdir files in captions not in directory\n";
  print MFILE "Total of $numlistnotdir files in captions not in directory\n";
  for ($ii=0; $ii<$numlistnotdir; $ii++) {
      print MFILE "$listnotdir[$ii]\n";
  }
  close(MFILE);
  if ($numlistnotdir>0) {
     print "Look at file $inpath/$mfn\n";
     die("Because files in captions are missing from directory, must stop.\n");
  }
# Main processing
  if (! $numcaps) {
     die("No captioned files to process");
  }
# create first file in chain
  my $ofn = $fnroot.'-1.htm'; 
# fstart subroutine
  $fcount=1; # file counter
  $hstring=$header." - ".$fcount;
  open (OFILE,">$ofn"); 
# NOTE: We're NOT checking if file exists.
#    procedure htmtop(var ofl: text; ofn: string; hstring: string);
# Files now open -- begin
  print OFILE "<HTML>\n";
  print OFILE "<HEAD>\n";
  print OFILE "<TITLE>$ofn</TITLE>\n";
  print OFILE "</HEAD>";
  print OFILE "<BODY>";
  print OFILE "<H2>$hstring</H2>\n";
  print OFILE "<BR><BR>\n";
  print OFILE "<h3>File created with program fotohtml (C) J C Nash, 1999</h3>\n";
  print OFILE "<BR><HL><BR>";
#  print OFILE "<BR><BR>\n";
  print OFILE "<UL>";
  my $filesonpage=0;
  print "fperpage=$fperpage, filesonpage=$filesonpage\n";
  $kk=0;
  while ($kk<$numcaps) { # loop over the captioned files
    if ($filesonpage < $fperpage) { # still can add a file
        print OFILE "<LI><IMG Height=380 align=top SRC=\"$capfiles[$kk]\"><BR>$capfiles[$kk]: $captions[$kk]</LI><BR>";
        $kk++; # decrement counter
        $filesonpage++;
    } else { # need to set up new page

       print OFILE "</UL><BR><BR>"; # to end the list of fotos on this page
       if ($kk<$numcaps) { 
          print OFILE "<A HREF=\"$fnroot-".($fcount+1).".htm\">Next file</A><BR>\n";
       }
# ?? more output here
       print OFILE "</BODY></HTML>\n";
       close(OFILE);
       print "File $ofn closed\n";
       $fcount++;
       $ofn = $fnroot.'-'.$fcount.".htm"; 
       $hstring=$header." - ".$fcount;
       open (OFILE,">$ofn"); 
       print OFILE "<HTML>\n";
       print OFILE "<HEAD>\n";
       print OFILE "<TITLE>$ofn</TITLE>\n";
       print OFILE "</HEAD>";
       print OFILE "<BODY>";
       print OFILE "<H2>$hstring</H2>\n";
       print OFILE "<BR><BR>\n";
       print OFILE "<h3>File created with program fotohtml (C) J C Nash, 1999</h3>\n";
       print OFILE "<BR><BR>\n";
       print OFILE "<A HREF=\"$fnroot-".($fcount-1).".htm\">Previous file</A>\n";
       print OFILE "<BR><HL><BR>";
       print OFILE "<UL>";
       $filesonpage=0; # reset file count for page
    }

  } # end loop over captioned files
die("Done");
#===============================================
# Perl trim function to remove whitespace from the start and end of the string
sub trim {
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}
# Left trim function to remove leading whitespace
sub ltrim {
	my $string = shift;
	$string =~ s/^\s+//;
	return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim {
	my $string = shift;
	$string =~ s/\s+$//;
	return $string;
}
#===============================================


