#!/local/bin/perl

sub rcsname {
    local ($_) = @_;

    return $_ if (/,v$/);

    if (defined($source)) {
	local($pattern) = $dest;
	$pattern =~ s/(\W)/\\$1/g;
	s/^$pattern/$source/;
    }

    if (-f ($_.",v")) {
	return $_.",v";
    }

    s-/[^/]*$-/RCS$&,v-;

    return $_;
}

sub normalname {
    local($_) = @_;

    if (defined($source)) {
	local($pattern) = $source;
	$pattern =~ s/(\W)/\\$1/g;
	s/^$pattern/$dest/;
    }

    (s-(RCS/|)([^/]*),v$-\2-) ||
	(s-(RCS/|)([^/]*)$-\2-);
    return $_;
}

sub revision_list
{
    local($fn) = @_;

    if ( ! -f $fn) {
	warn "No RCS file $fn\n";
	return ();
    }

    local(@rval);

    pipe(READ,WRITE) || die;

    $|=1; print ""; $|=0;

    local($childpid) = fork;
    if ($childpid) {
	close(WRITE);
    } else {
	close(READ);
	open(STDOUT, "<&WRITE");
	close(WRITE);
	exec "rlog", $fn;
	die "Unable to exec rlog on $fn\n";
    }

    local($_);

    while (<READ>) {
	chop;
	if (/^revision ([0-9.]+)/) {
	    push(@rval, $1);
	}
    }
    close(READ);

    waitpid($childpid,0);

    warn "funky return from rlog" unless ($? == 0) ;

    return @rval;
}


sub find_revision {
    local($rn, $nn, @REVS) = @_;

    local ($childpid, $_);

    foreach (@REVS) {
	$childpid = fork;
	if (!$childpid) {
	    open(STDOUT, ">/dev/null");
	    open(STDERR, ">/dev/null");
	    exec("rcsdiff", "-q", "-r$_", $rn, $nn);
	    die "Unable to exec rcsdiff -r$_\n";
	}
	waitpid($childpid, 0);
	last if $? > 1;		# some sort of gnarley error
	return $_ unless $?;
	print STDERR "Didn't match revision $_\n";
    }
    warn "Unable to match any RCS version for $nn";
    return "none";
}

sub usage {
    print STDERR <<EOF
Usage: $0 [ -conv /source=/dest ] filenames ...
EOF
    ;
    exit 1;
}



while (@ARGV) {
    $_ = shift;
    if ($_ eq "-conv") {
	$_ = shift;
	&usage unless /=/;
	$source=$`;
	$dest=$';
    } else {
	unshift(@ARGV, $_);
	last;
    }
}

foreach (@ARGV) {
    local($rn, $nn) = (&rcsname($_),&normalname($_));
#    print $_, " : \t", $rn, " ,\t", $nn, "\n";

    @REVISIONS = &revision_list($rn);
#    print join(",", @REVISIONS), "\n";

    $rev = &find_revision($rn, $nn, @REVISIONS);
    print "$_ revision: ", $rev, " (latest: ", $REVISIONS[0], ")\n";
}
