#!/usr/bin/perl
# Works with either Perl4 or Perl5, Perl4 is much faster.
#
# imgsizer -- correct image sizes in WWW pages
#
# by Eric S. Raymond <esr@thyrsus.com> 30 Jul 1996
#
# Fix up IMG tags in given documents to contain correct sizes.
# Requires the identify(1) program from the ImageMagick suite.
# To fix up sizes for non-local images it requires the httpget(1) script.
#
# Copy, use, and redistribute freely, but don't take my name off it and
# clearly mark an altered version.  Fixes and enhancements cheerfully 
# accepted.
#
# This is version 1.2.
#

# Anything that can fetch a URL defined on the command line 
# and dump it to stdout will do here. 
$fetcher = 'httpget';	

$out = "imgsizer-out$$";
if (@ARGV) {
	foreach $x (@ARGV) {
		$file = $x;
		$dir = &dirname($x);
		open(TEMP, ">$out")
			|| die("imgsizer: couldn't open tempfile $out \n");
		close(STDIN);
		if (!open(STDIN, "$file")) {
			print STDERR "imgsize: couldn't open $x for input\n";
		} else {
			select(TEMP);
			&sizefix;
			close(TEMP);
			if (system("cp $out $file")) {
				print STDERR "imgsize: couldn't replace ${file}\n}";
			}
		}
	}
	unlink($out);
}
else {
	$file = "stdin";
	&sizefix;
}

sub dirname
# return filename with the basename part stripped away
{
	my($file) = @_;
	if ($file =~ /\//) {
		$file =~ s:/[^/]*$::;
	} else {
		$file = ".";
	}
	return($file);
}

sub getchar
{
	$pushback = <STDIN> if (length($pushback) == 0);
	$char = substr($pushback, 0, 1);
	$pushback = substr($pushback,1);
	return $char;
}


sub sizefix
# Apply attrfix to the attributes in each image tag
{
	while (<STDIN>) {
		while (/<IMG\s+/i) {
			print $`; print $&;
			flush;
			$pushback = $';
			$tag = '';
			while (($char = &getchar) ne '>') {
				$tag .= $char;
			}
			print &attrfix($tag);
			print ">";
			$_ = $pushback;
		}
		print $_;
	}
}

sub error
{
	print STDERR "\"${file}\", line $.: $_[0]\n";
}


sub attrfix
# fix up a space-separated sequence of image attributes 
{
        $attribs = $_[0];

	if (!($attribs =~ /SRC="([^"]*)"/i)) {
		&error("image \"${attribs}\"' has no SRC attribute");
		return $attribs;
	}
	$url = $1;

	if ($url =~ /^http:/) {
		$image = "imgsizer-tmp$$";
		$status = system("$fetcher ${url} >${image}");
		if ($status) {
			&error("can't fetch $1");
			unlink("imgsizer-tmp$$");
			return $attribs;
		}
	}
	elsif (!($url =~ /^[a-z]+:/)) {
		$image = "$dir/$url";	# This catches local files
		
	}

	($name, $size) = split(' ', `identify ${image}`);
	unlink("imgsizer-tmp$$");
	if ($name =~ /:/) {
		&error("can't analyze included image ${image}");
		return $attribs;
	}
	if (!($size=~ /([0-9]+)x([0-9]+)/)) {
		&error("size field ${size} is ill-formed");
		return $attribs;
	}
	$xc = $1;
	$yc = $2;

	if ($attribs =~ /WIDTH=[0123456789]+/i) {
		$attribs = "$`WIDTH=${xc}$'";
	} else {
		$attribs .= " WIDTH=${xc}";
	}
	if ($attribs =~ /HEIGHT=[0123456789]+/i) {
		$attribs = "$`HEIGHT=${yc}$'";
	} else {
		$attribs .= " HEIGHT=${yc}";
	}
	return $attribs;
}
