#!/usr/bin/perl -w
use strict;

# This script was written by Rick Dean.
# It will make a lame attempt to create a _zoom.html
# file  with links to higher resolution
# _zoom.jpg pictures.

if ($#ARGV == -1) {  # if no command line arguments
  printf("usage: $0 filename.html [..]\n");
  exit(1);
};

sub zoomhtml {
  my ($filename) = @_;
  open(INFILE,"<$filename") || die "couldn't open $filename"; 
  print("process $filename\n");
  my $sourcedoc;
  read(INFILE,$sourcedoc,1000000) || die "couldn't read $filename";
  close(INFILE);
  my $outfilename = $filename;
  $outfilename =~ s/.html$/_zoom.html/i || die "$filename doesn't end in .html";

  my $changed=0;
  my @html = split('<',$sourcedoc);
  for(my $i=0;$i < $#html;$i++) {  # for every tag 
    if ($html[$i] =~ /(^[^>]*)/) {  # grab tag contents (everything until > )
      my $tag=$1;
      next unless $tag =~ /^a\s/i; # must begin with img
      next unless $tag =~ /href=(\S*)/; # must have href=
      my $href=$1;
      $href =~ s/^"(.*)"$/$1/;  # strip bounding double quotes
      next unless $href =~ /.jpg$/i;  # must be a link to a picture
      next if $href =~ /_zoom.jpg$/i;  # but not a zoom picture
      my $newref = $href;
      $newref =~ s/.jpg$/_zoom.jpg/i;  # change the image name
      if(!  -s $newref) { # if file doesn't exist (or has zero length)
        print("couldn't find $newref\n");
        next;  # skip because zoomed image doesn't exist 
      };
      next unless -s $newref; # zoom must exist and be non-zero in length
      $html[$i] =~ s/href=([^>\s]*)/href="$newref"/i or print("damn\n");
      $changed=1;
    };
  };

  if($changed) {
    open(OUTFILE,">$outfilename") || die "couldn't open $filename"; 
    print OUTFILE join('<',@html);
    close(OUTFILE);
    my $mode = (stat($filename))[2];
    chmod($mode,$outfilename);
  };
}


for my $filename (@ARGV) {
  next if $filename =~ /_zoom.html$/i;  # if end in _zoom.html case insensitive
  next if ! $filename =~ /.html$/i; # if doesn't end in .html
  zoomhtml($filename);
};



