#!/usr/bin/perl -w
#
#  This is a REAL QUICK HACK to add captions to JPG files. We'll replace it
#  with something more Rico Suave(tm) as time goes one.
#
#  Use --force to force the program to process all JPG files regardless of
#  whether an existing comment exists or not.
#
#  Use --oneline to get one line captions, ending when you hit enter.
#  (won't wait for . at last line to end it)
#
#  $Id: autocaption,v 1.7 2006/10/28 16:43:11 jjreynold Exp $
#  $Name: v1_1 $
#
use Getopt::Long;
use Term::ReadLine;
use vars qw($opt_force);

$size = '500x400';
$geom = "${size}+5+5";

my $term = new Term::ReadLine 'imageindex autocaption';
my $OUT = $term->OUT || \*STDOUT;

&GetOptions('force','oneline') or die ("Invalid flag\n");

if (scalar (@ARGV)) {
    @files = @ARGV;
}
else {
    while ($name = <*.jpg *.JPG *.jpeg *.JPEG>) {
	push (@files, $name);
    }
}

foreach my $name (@files) {
    printf $OUT ("Processing $name ...\n");
    $qname = quotemeta ($name);
    open (PIPE, "imageindex -caption $qname |") || die;
    $existing_caption = '';
    while (<PIPE>) {
	if (/: "(.*)"\s*$/) {
	    $existing_caption = $1;
	}
    }
    close (PIPE);
    if ($existing_caption) {
	printf $OUT ("Existing caption: \"$existing_caption\"\n");
	if (! defined ($opt_force)) {
	    printf $OUT ("Skipping this file. Use -force to re-do captions.\n\n");
	    next;
	}
    }
    else {
	printf $OUT ("No existing caption found.\n");
    }
    if (!defined($opt_oneline)) {
	printf $OUT ("Bringing up resized image. Enter a caption with \".\" last line:\n");
	printf $OUT ("(entering \".\" will re-use any previous caption)\n");
    } else {
	printf $OUT ("Bringing up resized image. Enter a caption:\n");
	printf $OUT ("(blank will re-use any previous caption)\n");
    }
    if ($pid = fork) {
	my $caption = "";
	my $prompt = "$name: ";
	while (defined ($_ = $term->readline($prompt)) ) {
	    warn $@ if $@;
	    if (defined($opt_oneline)) {
		$caption .= $_;
		last;
	    } elsif ($_ =~ /^\.$/) {
		last;
	    } else {
		$caption .= " $_";
	    }
	}
	chomp($caption);
	$term->addhistory($caption);
	$caption = quotemeta ($caption);
	if (($caption ne '') and ($caption ne '.')) {
	    printf $OUT ("Executing: imageindex -caption $qname $caption\n");
	    system ("imageindex -caption $qname $caption");
	}

	kill 15, $pid;

    }
    else {
	exec 'display', '-geometry', $geom, '-resize', $size, $name;
    }


}
