#!/usr/bin/perl
#
#DESCRIPTION
#   Run thru the files  listed,  or  everything  in  the  current  directory,
#   attempt  to  extract  a  name from the Z: lines, and rename the file with
#   that name's initials on the end of the line.

	push @INC, '.', 'sh', '../sh';
	require "Vopt.pm";
	require "abbr.pm";

#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
($me = $0) =~ s".*/"";
&Vopt($ENV{"V_$me"} || $ENV{"D_$me"} || $ENV{"T_$me"} || '1'); 

for $n (sort keys %n2i) {
	$i = lc($n2i{$n});
	$n = lc($n);
	$i2n{$i} = $n;
	$n2i{$n} = $i;
	print V "$me: '$i' <=> '$n'\n" if $V>3;
}

for $a (@ARGV) {
	if ($a =~ /^[-+](.*)/) {
	} else {
		if (@list = glob($a)) {
			push @files, @list;
			++$files;
		} else {
			print STDERR "$me: \"$a\" doesn't match any files.\n" if $V>0;
		}
	}
}

unless ($files) {
	@files = glob('*.abc');
}

file:
for $f (@files) {
	print V "$me: File \"$f\"\n" if $V>2;
	if ($f =~ /_..\./) {
		print V "$me: File \"$f\" already initialed.\n" if $V>1;
		next file;
	}
	unless (open(F,$f)) {
		 print STDERR "$me: Can't read \"$f\" ($!)\n" if $V>0;
		 next file;
	}
line:
	for $l (<F>) {
		if ($l =~ /^Z:.* by ([\w\s.]+)/) {
			$name = lc($1);
			$name =~ s/\s+$//;
			$name =~ s/\s+/ /;
			print V "$me: name \"$name\"\n" if $V>2;
			unless ($init = $n2i{$name}) {
				print STDERR "$me: No initials for \"$name\"\n" if $V>0;
				next line;
			}
			print V "$me: name \"$name\" is \"$init\"\n" if $V>2;
			$g = $f;
			$g =~ s/(\.\w+)$/_${init}$1/;
			$g =~ s/_\d+_$init/_$init/;
			print V "$me: file \"$f\" => \"$g\"\n" if $V>1;
			if (-f $g) {
				print STDERR "$me: Can't rename \"$f\" => \"$g\" (conflict)\n" if $V>0;
				next file;
			}
			if (rename($f,$g)) {
				print V "$me: file \"$f\" => \"$g\"\n" if $V>0;
			} else {
				print STDERR "$me: Can't rename \"$f\" => \"$g\" ($!)\n" if $V>0;
			}
			close F;
			next file;
		}
	}
	print V "$me: File \"$f\" contains no recognized name.\n" if $V>0;
	close F;
}
