#!/usr/bin/perl -w
#
#NAME
#  p_unpack - Unpack people file to single-name files.
#
#SYNOPSIS
#  p_unpack [file]..
#
#DESCRIPTION
#  This takes a "people"  file  and  splits  it  up  into  a  set  of
#  single-person files. The files are put inthe the directory "name",
#  and are named the same as the name on the N line, minus any  white
#  stuff.
#
#  This is a normal "perl filter", reading a list of files  or  STDIN
#  if there are no files named on the command line.
#
#EXAMPLE
#  cd people/
#  p_unpack Dancers Musicians name/*
#
#  In this example, we unpack the two files  Dancers  Musicians  into
#  the  name directory.  We also tell p_unpack to read all the name/*
#  files last, so that the data there will overwrite anything in  the
#  two big files.
#
#OPTIONS
#
#BUGS
#
#AUTHOR
#  John Chamber <jc@trillian.mit.edu>

$| = 1;
($P = $0) =~ s".*/"";	# Program name minus any directories.
$V = $ENV{"V_$P"} || 3;	# Verbosity.

# First, read in all the data for all the names, and extract all  the
# data fields into the %data table:
#
mkdir("name",0755) unless -d "name";

line:
for  $line (<>) {
	chomp $line;
	if (($flag,$datum) = ($line =~ /^([\w#%]+:*)\s+(.*)$/)) {
		if ($flag eq 'N') {
			print "Name: $datum\n" if $V>1;
			($name = $datum) =~ s/\W+//g;	# Only use alfanums from name.
			$names{"$name"} = $datum;		# Note each name.
			$info{"$name:"} = $datum;		# Name must be first.
		} else {
			$info{"$name:$flag"} = $datum;
			print "Data: $name:$flag\t= $datum\n" if $V>2;
		}
	} else {
		print "Drop: $line\n" if $V>2;
	}
}

# Next, run through the names in alphabetical order, and write a  new
# file for each name:
#
entry:
for $entry (sort keys %info) {
	$datum = $info{$entry};
	if ($entry =~ /^(\w+):$/) {
		close OUT;		# Close previous output file.
		$file = "name/$1";	# Path for this name.
		$datum = $names{$1};	# Get the full name.
		$writing = 0;	# Note that we can't write now.
		if (-f $file) {
			print STDERR "File \"$file\" replaced.\n" if $V>1;
		}
		unless (open(OUT,">$file")) {
			print STDERR "File \"$file\" unwritable ($!)\n" if $V>0;
			next entry;
		}
		$writing = 1;	# We can write now.
		print OUT "N	$datum\n";
	} elsif (($nm,$flag) = ($entry =~ /^(\w+):(.*)/)) {
		print OUT "$flag	$datum\n" if $writing;
		
	}
}
