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

# Used to change the names of the image files generated by latex2html from imgxx.png
#  to meaningful names.  Provision is made to go either from or to the meaningful names.
#  The meaningful names are obtained from a file called imagename_translations, which
#  is generated by extensions to latex2html in the make_image_file subroutine in 
#  bacula.perl.

# Opens the file imagename_translations and reads the contents into a hash.
# The hash is creaed with the imgxx.png files as the key if processing TO
#  meaningful filenames, and with the meaningful filenames as the key if 
#  processing FROM meaningful filenames.
# Then opens the html file(s) indicated in the command-line arguments and
#  changes all image references according to the translations described in the 
#  above file.  Finally, it renames the image files.
#
# Original creation: 3-27-05  by Karl Cunningham.
#   Modified 5-21-05 to go FROM and TO meaningful filenames.
#
my $TRANSFILE = "imagename_translations";
my $path;

# Loads the contents of $TRANSFILE file into the hash referenced in the first 
#  argument. The hash is loaded to translate old to new if $direction is 0, 
#  otherwise it is loaded to translate new to old.  In this context, the 
#  'old' filename is the meaningful name, and the 'new' filename is the 
#  imgxx.png filename.  It is assumed that the old image is the one that
#  latex2html has used as the source to create the imgxx.png filename.
# The filename extension is taken from the file 
sub read_transfile {
	my ($trans,$direction) = @_;

	if (!open IN,"<$path$TRANSFILE") {
		print "WARNING:  Cannot open image translation file $path$TRANSFILE for reading\n";
		print "   Image filename translation aborted\n\n";
		exit 0;
	}

	while (<IN>) {
		chomp;
		my ($new,$old) = split(/\001/);

		# Old filenames will usually have a leading ./ which we don't need.
		$old =~ s/^\.\///;

		# The filename extension of the old filename must be made to match
		#  the new filename because it indicates the encoding format of the image.
		my ($ext) = $new =~ /(\.[^\.]*)$/;
		$old =~ s/\.[^\.]*$/$ext/;
		if ($direction == 0) {
			$trans->{$new} = $old;
		} else {
			$trans->{$old} = $new;
		}
	}
	close IN;
}
	
# Translates the image names in the file given as the first argument, according to 
#  the translations in the hash that is given as the second argument.
#  The file contents are read in entirely into a string, the string is processed, and
#  the file contents are then written. No particular care is taken to ensure that the
#  file is not lost if a system failure occurs at an inopportune time.  It is assumed
#  that the html files being processed here can be recreated on demand.
#
# Links to other files are added to the %filelist for processing.  That way,
#  all linked files will be processed (assuming they are local).
sub translate_html {
	my ($filename,$trans,$filelist) = @_;
	my ($contents,$out,$this,$img,$dest);
	my $cnt = 0;

	# If the filename is an external link ignore it.  And drop any file:// from
	#  the filename.
	$filename =~ /^(http|ftp|mailto)\:/ and return 0;
	$filename =~ s/^file\:\/\///;
	# Load the contents of the html file.
	if (!open IF,"<$path$filename") {
		print "WARNING:  Cannot open $path$filename for reading\n";
		print "  Image Filename Translation aborted\n\n";
		exit 0;
	}

	while (<IF>) {
		$contents .= $_;
	}
	close IF;

	# Now do the translation...
	#  First, search for an image filename.
	while ($contents =~ /\<\s*IMG[^\>]*SRC=\"/si) {
		$contents = $';
		$out .= $` . $&;
		
		# The next thing is an image name.  Get it and translate it.
		$contents =~ /^(.*?)\"/s;
		$contents = $';
		$this = $&;
		$img = $1;
		# If the image is in our list of ones to be translated, do it
		#  and feed the result to the output.
		$cnt += $this =~ s/$img/$trans->{$img}/ if (defined($trans->{$img}));
		$out .= $this;
	}
	$out .= $contents;

	# Now send the translated text to the html file, overwriting what's there.
	open OF,">$path$filename" or die "Cannot open $path$filename for writing\n";
	print OF $out;
	close OF;

	# Now look for any links to other files and add them to the list of files to do.
	while ($out =~ /\<\s*A[^\>]*HREF=\"(.*?)\"/si) {
		$out = $';
		$dest = $1;
		# Drop an # and anything after it.
		$dest =~ s/\#.*//;
		$filelist->{$dest} = '' if $dest;
	}
	return $cnt;
}
	
# REnames the image files spefified in the %translate hash.
sub rename_images {
	my $translate = shift;
	my ($response);

	foreach (keys(%$translate)) {
		$response = `mv -f $path$_ $path$translate->{$_} 2>&1`;
		$response and print "ERROR from system    $response\n";
	}
}

#################################################
############# MAIN #############################
################################################

# %filelist starts out with keys from the @ARGV list.  As files are processed,
#  any links to other files are added to the %filelist.  A hash of processed
#  files is kept so we don't do any twice.

# The first argument must be either --to_meaningful_names or --from_meaningful_names

my (%translate,$search_regex,%filelist,%completed,$thisfile);
my ($cnt,$direction);

my $arg0 = shift(@ARGV);
$arg0 =~ /^(--to_meaningful_names|--from_meaningful_names)$/ or
	die "ERROR: First argument must be either \'--to_meaningful_names\' or \'--from_meaningful_names\'\n";

$direction = ($arg0 eq '--to_meaningful_names') ? 0 : 1;

(@ARGV) or die "ERROR: Filename(s) to process must be given as arguments\n";

# Use the first argument to get the path to the file of translations.
my $tmp = $ARGV[0];
($path) = $tmp =~ /(.*\/)/;
$path = '' unless $path;

read_transfile(\%translate,$direction);

foreach (@ARGV) {
	# Strip the path from the filename, and use it later on.
	if (s/(.*\/)//) {
		$path = $1;
	} else {
		$path = '';
	}
	$filelist{$_} = '';

	while ($thisfile = (keys(%filelist))[0]) {
		$cnt += translate_html($thisfile,\%translate,\%filelist) if (!exists($completed{$thisfile}));
		delete($filelist{$thisfile});
		$completed{$thisfile} = '';
	}
	print "translate_images.pl: $cnt image filenames translated ",($direction)?"from":"to"," meaningful names\n";
}

rename_images(\%translate);
