#!/usr/bin/perl

=head1 NAME
  MLphone - convert mailing list to phone book

=head1 SYNOPSIS
  MLphone [opt] [infile]...

=head1 DESCRIPTION
 This reads one or more "mailing list" files, and writes a phone book
 to stdout.

 Mailing list files have entries of the form:

N	John Chambers
Phv	617/647-1813	[answering machine]
Phm	617/647-1839	[modem]
I	accordion, fiddle, flutes [CNSX]
A1	33 Cedarwood Av
A2	Waltham MA 02154
Eh	minya.bcs.org!jc
Eh	harvard.edu!minya.uucp!jc
Eh	trillian.mit.edu!minya.uucp!jc
Ew	jc0@gte.com

 Each line starts with an identifier in col 1, some  whitespace,  and
 the data in the rest of the line. The preferred whitespace after the
 id field is a tab, but we don't care.  However,  this  program  does
 replace  whatever  whitespace  is  there  with  a tab, as part of at
 attempt to put everything into a canonical format.

 Entries are sorted on the name, indicated by the 'N' entry, which is
 expected to be the first line. Some problems may arise if some other
 id  line  is  first,  so  try  to  always create new entries with an
 initial 'N' line.

 Our basic approach is to read all the entries into a set  of  tables
 indexed by name.  When we run out of input, we run thru the names in
 alphabetical order, and output each person's data.

=head1 AUTHOR
  John Chambers <jc@trillian.mit.edu>

=cut


$| = 1;
($me = $0) =~ s".*/"";
$D = $ENV{"D_$me"} || $ENV{"V_$me"} || 0;
@name = ();	# Current set of names.

for $line (<>) {
	$line =~ s/\s+$//;
	if ($line eq '' ) {
		print "New entry.\n" if $D;
		@name = ();
	} elsif (($id,$xx) = ($line =~ /^(\S+)\s+(.*)/)) {
		print "Found id \"$id\" data \"$xx\"\n" if $D;
		if ($id eq 'N') {
			print "Found name \"$xx\"\n"if $D;
			push(@name,$xx);
		} else {
			for $n (@name) {
				$desc = "$id $n";	# Descriminator for this datum.
				$data{$desc} = $xx;	# Remember it.
				$ids{$n} .= "$id,";	# List of person's ids.
			}
		}
	} else {
		print "$0: Drop \"$line\"\n" if $D;
	}
	print "Done with \"$line\"\n" if $D;
}
$i = 0;

%lbl = (
	'Ph',	'home',
	'Pw',	'work',
	'Pc',	'car',
	'Pm',	'mobile',
);
for $n (sort keys %ids) {
#	print "\nN\t$n\n";
	for $id (sort split(',',$ids{$n})) {
		if ($id =~ /^P/) {		# Phone entry?
			$l = $lbl{$id} || 'phone';
			$desc = "$id $n";	# Descriminator for this datum.
			if ($xx = $data{$desc}) {
				print "$l\t$xx\t$n\n";
				$data{$desc} = '';	# Don't produce it again.
			}
		}
	}
}
print "\n";
print "$0: Done.\n" if $D;

exit 0;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

