#!/usr/bin/perl -w

$identify = "/usr/bin/identify";
$convert = "/usr/bin/convert";

@default_sizes = (192, 384, 768, 1536, 3072);
@sizes = ();

$verbose = 0;
$bordercolor = "black";
$comment = undef;

sub usage() {
    print <<"EOF"
Usage: $0 [OPTIONS] file [file2 ....]
Options:

-h		Print this help message.
-v		Generate verbose output.
-nb             Do not put a border around the image.
-bc COLOR       Use border color COLOR.
-c COMMENT      Annotate images with COMMENT.  Default is no comment.
-s SIZE         Print images so that the longest side is SIZE pixels.
                Multiple values can be specified.
                Defaults are 192, 384, 768, 1536, 3072---in landscape mode,
                with a standard 35mm 3:2 aspect ratio, this yields images 
		with the following sizes: 192x128, 384x256, 768x512,
		1536x1024, and 3072x2048.

Converts the given image files (usally TIFF or JPEG) into JPEG files
with multiple resolutions, suitable for printing or web pages.  An
original such as file.tif or file.jpg is converted into file.SIZE.jpg,
for each value of SIZE (for example, file.192.jpg, file.384.jpg, etc.).
EOF
    ;
    exit 1;
}

sub parse_args() {
    usage() unless @ARGV;
    while ($_ = shift(@ARGV)) {
	if (/^-h$/)  { usage(); }
	if (/^-v$/)  { ++$verbose; next; }
	if (/^-nb$/) { $bordercolor = undef; next; }
	if (/^-bc$/) {
	    usage() unless @ARGV;
	    $bordercolor = shift(@ARGV) unless !defined($bordercolor);
	    next;
	}
	if (/^-c$/) {
	    usage() unless @ARGV;
	    $comment = shift(@ARGV);
	    next;
	}
	if (/^-s$/) {
	    usage() unless @ARGV;
	    push @sizes, shift(@ARGV);
	    next;
	}
	unshift(@ARGV, $_);
	last;		   # not a known option, so assume it's a file
    }
    @sizes = @default_sizes unless @sizes;
}

sub process_file($$) {
    my ($from, $base) = @_;

    print "Processing: $from -> $base\n" if $verbose;
    my $out = `$identify $from`;
    $out =~ / (\d+)x(\d+) /;
    my ($x, $y) = ($1, $2);
    print "\tx=$x, y=$y\n" if $verbose;

    for my $sz (@sizes) {
	print "\t Generating size $sz: " if $verbose;
	my $q = ($sz < 500 ? 75 : ($sz < 1000 ? 85 : 95));
	my $com = "$convert -geometry ${sz}x${sz} -quality $q";
	if (defined($bordercolor)) {
	    my $bsz = int($sz * 2/192); # 2px border for 192px image
	    $com .= " -border ${bsz}x${bsz} -bordercolor $bordercolor";
	}
	if (defined($comment)) {
	    $com .= " -comment \"$comment\"";
	}
	my $out = "${base}.${sz}.jpg";
	if (-e $out) {
	    warn("File $out already exists; skipping\n");
	    next;
	}
	$com .= " $from $out";
	print "$com\n" if $verbose;
	system($com);
    }
}

parse_args();
select(STDOUT); $| = 1;		# make unbuffered

if ($verbose) {
    my $now = localtime;
    print "mjpg start: $now\n";
}
while (my $file = shift(@ARGV)) {
    $file =~ /(.*\/)?([^\.]*)(\.[^\.])?/;
    my $base = $2;
    process_file($file, $base);
}
if ($verbose) {
    my $now = localtime;
    print "mjpg end: $now\n";
}

0;
