#!/usr/bin/perl -w

#
# dbcolcreate
# Copyright (C) 1991-1998 by John Heidemann <johnh@isi.edu>
# $Id: dbcolcreate,v 1.19 1999/11/23 02:04:29 johnh Exp $
#
# This program is distributed under terms of the GNU general
# public license, version 2.  See the file COPYING
# in $dblibdir for details.
#
sub usage {
	print STDERR <<END;
usage: $0 col-name null-value [col-name null-value...]
	Create a new columns and populate them with values.

Sample input:
#h test
a
b

Sample command:
cat data.jdb | dbcolcreate foo FOO

Sample output:
#h      test    foo
a       FOO
b       FOO

END
    exit 1;
}


BEGIN {
    $dblibdir = "/usr/local/lib/jdb";
    push(@INC, $dblibdir);
}
use DbGetopt;
require "$dblibdir/dblib.pl";

my(@orig_argv) = @ARGV;
my($prog) = &progname;
$debug = 0;
my($dbopts) = new DbGetopt("d?", \@ARGV);
my($ch);
while ($dbopts->getopt) {
    $ch = $dbopts->opt;
    if ($ch eq 'd') {
	$debug++;
    } else {
	&usage;
    };
};

# Must be even number of args.
&usage if ($#ARGV == -1 || $#ARGV % 2 != 1);
%newcols = @ARGV;
# Remember names in order.
foreach (0..$#ARGV) {
    push(@newcols, $ARGV[$_])
	if ($_ % 2 == 0);
};

&readprocess_header;

#
# Don't recreate columns that already exist.
#
foreach (@newcols) {
    die "$prog: pre-existing column $_.\n"
	if (defined($colnametonum{$_}));
};

#
# Create new columns.
#
foreach (@newcols) {
    $col_f{$_} = &col_create($_);
    $code .= '$f[' . $col_f{$_} . "] = '" . $newcols{$_} . "';\n";
};
print STDERR $code
    if ($debug);

#
# Pass through data w/ new values.
#
&write_header();

my($loop) = q[
    while (<STDIN>) {
        &pass_comments && next;
        &split_cols;
] . $code . q[    
        &write_cols;
    };
];
eval $loop;
$@ && die ("$prog: interal eval error ``$@''.\n");

print "#  | $prog " . join(" ", @orig_argv) . "\n";
exit 0;

if (0) {
    my $x;
    $x = $colnametonum{'foo'};
}
