#!/usr/bin/perl

#
# dblistize
# Copyright (C) 1991-1998 by John Heidemann <johnh@isi.edu>
# $Id: dblistize,v 1.15 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 <<END;
usage: $0 [-d]

    Convert normal tabular format to a list-based format
    where each column value is on a line by itself tagged
    with its column-name.  ``Rows'' are separated by two blank lines.
    Convert back with dbcolize.
    
    When you have many columns and few rows a list-based format
    is easier to read.

Sample input:
#h      experiment      mean    stddev  pct_rsd conf_range      conf_low       conf_high        conf_pct        sum     sum_squared     min     max     n
ufs_mab_sys     37.25 0.070711 0.18983 0.6353 36.615 37.885 0.95 74.5 2775.1 37.2 37.3 2
ufs_rcp_real    271.2 9.4752 3.4938 85.13 186.07 356.33 0.95 542.4 1.4719e+05 264.5 277.9 2
#  | /home/johnh/BIN/DB/dbmultistats experiment duration

Sample command:
cat data.jdb | dblistize

Sample output:
#L      experiment      mean    stddev  pct_rsd conf_range      conf_low       conf_high        conf_pct        sum     sum_squared     min     max     n
experiment:  ufs_mab_sys
mean:        37.25
stddev:      0.070711
pct_rsd:     0.18983
conf_range:  0.6353
conf_low:    36.615
conf_high:   37.885
conf_pct:    0.95
sum:         74.5
sum_squared: 2775.1
min:         37.2
max:         37.3
n:           2

experiment:  ufs_rcp_real
mean:        271.2
stddev:      9.4752
pct_rsd:     3.4938
conf_range:  85.13
conf_low:    186.07
conf_high:   356.33
conf_pct:    0.95
sum:         542.4
sum_squared: 1.4719e+05
min:         264.5
max:         277.9
n:           2

#  | /home/johnh/BIN/DB/dbmultistats experiment duration
#  | /home/johnh/BIN/DB/dblistize 

Related programs:
    dbcolize

END
    exit 1;
}

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

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


&readprocess_header;
$code = '';
$maxcolwidth = 0;
foreach (@colnames) {
    $maxcolwidth = length($_) if (length($_) > $maxcolwidth);
};
foreach (@colnames) {
    $code .= "print '$_: " . (" " x ($maxcolwidth - length($_))) .
		"', " . '$f[' . $colnametonum{$_} . '], "\n";' . "\n";
};
$code .= 'print "\n";' . "\n";
if ($debug) {
    print $code;
    exit 1;
};

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

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