#!/usr/local/bin/perl

#
# dbcolsplittorows
# Copyright (C) 1991-2005 by John Heidemann <johnh@isi.edu>
# $Id: dbcolsplittorows,v 1.3 2005/02/26 18:48:41 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 <<END;
usage: $0 [-C ElementSeperator] column

Options:

    -C sep    gives the separator
    -e null	gives the value for empty (null) entries

Split column into pieces, outputting one row for each piece.

By default, any empty fields are ignored.
If an empty field value is given with -e, then they produce output.

When a null value is given, empty fields at the beginning and end of
lines are suppressed (like perl split).  Unlike perl, if ALL fields
are empty, we generate one (and not zero) empty fields.

Sample input:
#h name uid
John_Heidemann  2274
Greg_Johnson    2275
Root    0
# this is a simple database
#  | dbcol fullname uid
#  | dbcolrename fullname name

Sample command:
cat data.jdb | dbcolsplittorows name

Sample output:
#h name uid
John    2274
Heidemann       2274
Greg    2275
Johnson 2275
Root    0
# this is a simple database
#  | dbcol fullname uid
#  | dbcolrename fullname name
#  | dbcolsplittorows name
END
    exit 1;
}

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

@orig_argv = @ARGV;
my($prog) = &progname;
$elem_separator = "_";
my($dbopts) = new DbGetopt("C:e:?", \@ARGV);
my($null_value) = undef;
my($ch);
while ($dbopts->getopt) {
    $ch = $dbopts->opt;
    if ($ch eq 'C') {
    	$elem_separator = $dbopts->optarg;
    } elsif ($ch eq 'e') {
    	$null_value = $dbopts->optarg;
    } else {
	&usage;
    };
};

&usage if ($#ARGV != 0);

&readprocess_header;
&write_header;

my $colf = $colnametonum{$ARGV[0]};
die ("$prog: unknown column ``$ARGV[0]''.\n")
    if (!defined($colf));

while (<STDIN>) {
    &pass_comments && next;
    &split_cols;
    my(@subf) = split(/$elem_separator/, $f[$colf]);
    push @subf, $null_value if ($#subf == -1 && defined($null_value));
    foreach (@subf) {
	if (!defined($_) || $_ eq '') {
	    next if (!defined($null_value));
	    $_ = $null_value;
	};
	$f[$colf] = $_;
        &write_cols;
    };
};

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