#!/usr/bin/perl
#
# ps2gif xres yres ifile [ofile]
#
# Convert  a postscript file to GIF, using the gs (GhostScript) command.  The
# resolution defaults to 100,  which  is  a  readable  compromise  for  small
# screens.  The ifile should be a postscript file. You can omit a .ps suffix
# and we'll assume it.
#
# Author: John Chambers <jc@trillian.mit.edu>

($P = $0) =~ s".*/"";
($ENV{"V_$P"} . ' 1') =~ /(\d+)/;	# Verbose level
$V = int($1);

print STDERR "$P: 0='$0' P='$P'\n" if $V>1;
$ENV{PATH} = '/hda/home/jc/bin:/hda/home/jc/sh:/usr/bin:/usr/sbin:/usr/local/bin';
$ENV{LD_LIBRARY_PATH} = '/lib:/usr/lib:/var/lib:/usr/local/lib:/usr/X11R6/lib:/hda/root/lib:/hda/root/usr/lib:/hda/root/var/lib';

$xres = shift || 200;
$yres = shift || 200;

print STDERR "$P: xres='$xres' yres='$yres'\n" if $V>1;

file: for $arg (@ARGV) {
	if (!$ifile) {
		$ifile = $arg;	# Root file name
		print STDERR "$P: ifile=\"$ifile\"\n" if $V>1;
	} elsif (!$ofile) {
		$ofile = $arg;	# Root file name
		print STDERR "$P: ofile=\"$ofile\"\n" if $V>1;
	} else {
		print STDERR "$P: Extra arg \"$arg\" ignored.\n" if $V>1;
	}
}
unless ($ifile) {
	print STDERR "$P: Input file \"$ifile\" not found.\n" if $V>0;
	exit 1;
}
unless ($ofile) {
	print STDERR "$P: Output file \"$ofile\" not found.\n" if $V>0;
	if ($ifile =~ m/(.*)\.e*ps$/i) {	# Is it some sort of PS file?
		$ofile = "$1.gif";
	} else {		# If not, just add a ".gif" suffix.
		$ofile = $ifile . '.gif';
	}
}
print STDERR "PATH='" . $ENV{PATH} . "'\n" if $V>1;
&showcmd('gs');
&showcmd('pnmcrop');
&showcmd('ppmtogif');
$cmd = "gs -q -DNOPAUSE -sDEVICE=ppmraw -r${xres}x${yres} -sOutputFile='|pnmcrop|ppmtogif -interlace >$ofile' -- $ifile";
print STDERR "$P: cmd=\"$cmd\"\n" if $V>1;
system $cmd;
exit $?;

sub lsend {
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Send a line to the logfile.  
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#	if ($Lopen) {
#		print L @_;
#	} else {
#		print STDERR "$0($$): No logfile.\n";
		print STDERR @_,"\n";
#	}
}

sub showcmd { my $F='showcmd';
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Show the path to a command. This is done by calling which(1), which has a
# chance of being considered "tainted" under mysterious circumstances.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($cmd) = @_;
	local($pth);
	$pth = `which $cmd`;
	$pth =~ s/^[\r\n]+//;
	$pth =~ s/[\r\n]+$//;
	print STDERR "$P: '$cmd' is $pth\n" if $V>1;
#	return $pth;	# We don't use the path.
}
