#!/s/perl/bin/perl
# $Id: clean_fields.pl,v 1.2 1995/07/03 21:23:35 bates Exp $

###
### Clean the fields in the Statistics Department database.
### Strip leading and trailing blanks in the fields but make sure that
### entirely blank fields have one blank in them.
###

require 5.000;

$Usage = "Usage: $0 db_name\n";
die ($Usage) unless $#ARGV == 0;	# Check argument count
$dbName = $ARGV[0];

$DIR = '/p/stat/Data/admin/';	# Set the directory
$FSEP = "\t";			# separate fields by tabs

$DB = $DIR . $dbName;		# Name of database
$FORM = $DB . ".form";		# Name of emacs-lisp form definition
				# for database
open(FORM, "< $FORM") ||
    die ("Unable to open form file $FORM: $!\n");
undef $/; $form = <FORM>; $/ = "\n"; # slurp entire form file into a
				     # string
die "$FORM does not define the fields!\n"
    unless ($form =~ /\(forms-enumerate[^']*'\(([^\)]*)/);
@FIELDS = grep(!/^$/, split(/\s+/, $1));

rename($dbName, $dbName . ".bak") || # create a backup of the file
    die ("Unable to move $dbName to ${dbName}.bak: $!\n");
open(INPUT, "< $dbName.bak") ||
    die ("Unable to open $dbName.bak for input: $!\n");
open(OUTPUT, "> $dbName") ||
    die("Unable to open $dbName for output: $!\n");

$flen = $#FIELDS;

while (<INPUT>) {
    chop;
    $rcount++;			# keep track of the record count
    @thisRec = split(/$FSEP/, $_);
    die "Record $rcount has $#thisRec fields.  It should have $flen.\n"
	unless $flen == $#thisRec;
    for (@thisRec) {
	s/^\s+//;		# strip leading spaces
	s/\s+$//;		# strip trailing spaces
	s/^$/ /;		# replace entirely blank fields with
				# one blank
    }
    print OUTPUT join($FSEP, @thisRec), "\n";
}
