#!/usr/bin/perl -P
#
# Cdiff [options] file1 file2
#
# ClearCase diff. So far, this program only handles the two-file case.
# It  does a comparison of the files after stripping away any lines up
# to one that says 'End ClearCase Header'.  It then compares the  rest
# of  the  lines,  and exits with status zero if they are the same and
# nonzero if they are different.  A few options are recognized:
#
# -b means to treat all blank strings as a single blank.  Thus "a + b"
#    is the same as "a  + b" but differs from "a+b".
#
# -w is like -b, but blank strings and lines are ignored. Thus "a + b"
#    is the same as "a  + b" or "a+b".

#include "dbg.pl"

for $a (@ARGV) {
	if ($a =~ /^-b/) {
		$bfl = 1;
		$spat = '\s*';
		$srpl = ' ';
	} elsif ($a =~ /^-w/) {
		$wfl = 1;
		$spat = '\s*';
		$srpl = '';
	} elsif (!$f1) {
		$f1 = $a;
	} elsif (!$f2) {
		$f2 = $a;
	} else {
		print STDERR "$0: Extra arg \"$f\" ignored.\n";
	}
}
if (!f2) {
	print STDERR "Usage: $0 [options] file1 file2\n";
	exit -1;
}
open(F1,"<$f1") || die "$0: Can't read \"$f1\" [$!]\n";
open(F2,"<$f2") || die "$0: Can't read \"$f2\" [$!]\n";

for $l1 (<F1>) {
	if ($l1 =~ /End ClearCase Header/) {
		$d1 = $n1;	# Number of deleted lines in F1.
		@x1 = ();	# Empty out its data vector.
		$n1 = 0;
		next;
	}
	$l1 =~ s/$spat/$srpl/g if ($spat);
	next if ($wfl && !$l1);
	push(@x1,$l1);	# Add line to data vector for F1.
	++$n1;
}
for $l2 (<F2>) {
	if ($l2 =~ /End ClearCase Header/) {
		$d2 = $n2;	# Number of deleted lines in F2.
		@x2 = ();	# Empty out its data vector.
		$n2 = 0;
		next;
	}
	$l2 =~ s/$spat/$srpl/g if ($spat);
	next if ($wfl && !$l2);
	push(@x2,$l2);	# Add line to data vector for F2.
	++$n2;
}
if ($n1 != $n2) {
	D "Sizes $n1, $n2 differ.\n" D2;
	exit 1;		# They are different sizes.
}
for ($l = 0; $l < $n1; ++ $l) {
	if ($x1[$l] ne $x2[$l]) {
		D "Line $l[+$d1,$d2] differs.\n" D2;
		exit 2;	# Line $l differs.
	}
}
