#!/bin/perl
#
# $Id: rr.pl,v 1.8 2003/08/10 14:53:31 dlk Exp $
# $Source: /home/dlk/src/frameit/RCS/rr.pl,v $
#
# (C) Copyright 2000, David L. Kensiski
#
# Rotate an image right or left, depending on how called
# Also finds associated images and rotates them

use strict;

# Parse cmd args
my $opt_v=shift(@ARGV) if ($ARGV[0] eq '-v');

# Get file list
my @files = @ARGV;
die "Usage: $0 [-v] file...\n" if ($#files < 0);

# Figure out if we're a righty or a lefty or a flippy
my $prog = (reverse(split(/\//, $0)))[0];
my $rotate;
if ($prog eq 'rr') {
	$rotate = 'pnmflip -cw';			# Right
} elsif ($prog eq 'rl') {
	$rotate = 'pnmflip -ccw';			# Left
} elsif ($prog eq 'xy' || $prog eq 'flip') {
	$rotate = 'pnmflip -xy | pnmflip -rotate270';	# Horizontal
} else {
	die "$0: how do I $prog?\n";
}

# First build an array of work to do
my %workfiles;
for my $file ( @files ) {

	# First check readability of file
	if (! -r $file) {
		warn "$0: $file", $! ? ": $!\n" : ": stat failed\n";
		next;
	}

        # Get base filename
        my ($base, $suff, $ext, $mavica);
        if ($file =~ /([^.]*)\.(.*)/) {
                $base = $1;
                $ext = $2;
        } else {
                warn "$0: unable to parse $file; skipping\n";
                next;
        }

	# Does it match a Mavica filename?
	if (($base =~ /^(mvc-[0-9]+)([a-z])$/) ||
	    ($base =~ /^(dsc[0-9]+)([a-z])?$/)) {
		$base = $1;
		$suff = $2;
		$mavica = 1;
	}

	print " $base $suff . $ext\n" if ($opt_v);

	# Make sure we know what we're doing
	if ($ext !~ /(jpg|jpeg)/i) {
		warn "$file: unknown file type $ext; skipping\n";
		next;
	}

	# Make a hash of files to process (eliminates duplicates)
	$workfiles{"$file"}++;

	# If it's a Mavica file, see if there are others
	if ($mavica) {
		foreach my $fn ( <$base?.$ext> ) {
			next if ($fn =~ /-orig/);
			$workfiles{"$fn"}++;
		}
	}

	# Back up original if not already done
	my $bkup = $file;
	$bkup =~ s/(.*)\.(jpe?g)/\1-orig.\2/i;
	if (! -r $bkup) {
		print "Backing up $file to $bkup\n" if ($opt_v);
		system('/bin/mv', '-f', $file, $bkup);
		system('/bin/cp', $bkup, $file);
	}
}

print "Work files: ", join(' ', sort(keys(%workfiles))), "\n" if ($opt_v);

# Now do the work
foreach my $file ( sort ( keys ( %workfiles ) ) ) {

	print "Rotating $file $prog\n" if ($opt_v);

	# Do it all in one filter
	my $cmd = "djpeg '$file' | $rotate | cjpeg > '$file.new'";

	print " system($cmd)\n" if ($opt_v);
	my $stat = system($cmd);

	# Did pipeline fail?
	if ($stat>>8 != 0) {
		warn "$0: rotation returned $stat\n";
		warn "$0: system($cmd)\n";
		next;
	}

	# If not, rename file
	warn " renaming $file.new to $file\n" if ($opt_v);
	system("mv '$file.new' '$file'");
}
