#!/usr/bin/perl

use strict;
use Getopt::Std;

use vars qw(
    $opt_h $opt_q $opt_d $opt_c
);

$opt_h  = "";     # appended header for shell pipe implies q ( ex. "ls -l" )
$opt_q  =0;       # quote mode
$opt_d  =0;       # include duplicated original
$opt_c  =2;       # conents compare mode

getopts('h:qdc');

open(FIND, "(" . 
   "find ~/Pictures/iPhoto/Originals -name '*.jpg' -ls -or -name '*.JPG' -ls ;" .
   " ) |  sort -n -k 7 |"); 

my $head = $opt_h;
my $quote = $opt_q;
my $dup = $opt_d;
my $nocheck = !$opt_c;
if ($opt_c==1) { $nocheck= 1; }
if ($opt_c==2) { $nocheck= 0; }
# print "$opt_c $nocheck\n";

if ($opt_h) {
    $head .= " ";
    $quote = 1;
}

my $size = 0;
my @prev;
while(<FIND>) {
    my @data = split;
    if ($data[6]==$size && $size>0) {
       my $f1 = "@data[10..$#data]";
       for my $f2 ( @prev ) {
	   my $r1; my $r2;
	   if (! $nocheck) {
	       open(F1,$f1);   sysread(F1,$r1, 4096*2); close(F1);
	       open(F2,$f2);   sysread(F2,$r2, 4096*2); close(F2);

	       substr($r1,0xb0,80) = '';
	       substr($r2,0xb0,80) = '';
	   }
	   if ($nocheck || $r1 eq $r2 ) {

		my $now =  "@data[10..$#data]\n"; 
		my $prev = $f2;
		if ($quote) {
		    $now =~ s/ /\\ /g;
		    $prev =~ s/ /\\ /g;
		}
		print "$head$now";
		print "$head$prev" if ($dup);

		# print "! @data[10..$#data]\n"; 
		# print "     and $prev";
	   }
       }
    } else {
	@prev = ();
    }
    $size = $data[6];
    # $prev = $_;
    push(@prev , "@data[10..$#data]\n"); 
}

