#!/usr/bin/perl
# *********************************************************************
#  Original code: tbl2lst,v 2.7 1993/03/29 13:34:46 hobbs
#
#  Adapted to NoSQL by Carlo Strozzi <carlos@linux.it>.
#
#  viewtable: comfortable NoSQL table viewer.
#  Copyright (C) 1998-2003 Carlo Strozzi <carlos@linux.it>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# *********************************************************************
#  $Id: viewtable,v 1.2 2003/03/17 10:10:46 carlo Exp $

$NOSQL_INSTALL = $ENV{'NOSQL_INSTALL'};
$NOSQL_INSTALL = "/usr/local/nosql" if not $NOSQL_INSTALL;

$0 =~ s-.*/-- ;
$: = "\n " ;    # default line break list (white space)
$LEN = 80 ; # default line length
$frm = "format STDOUT = \n^" ;
while ( $ARGV[0] =~ /^-/ ){         # Get args
    $_ = shift ;
    if( /^-l(\d+)/ || /^--line-length=(\d+)/ ){ $LEN = $1 ; next ; }
    if( /^-h.*/ || /^--help$/ ){
	$HelpInfo = `grep -v '^#' $NOSQL_INSTALL/help/viewtable.txt`;
	print "$HelpInfo" ;
	exit 1 ;
    }
    die "\n$0: unknown option: $_\n", "For help type \"$0 --help\".\n" ; }
$lim = $LEN - 16 ;      # max line space for long data fields
$frm .= '<' x ($lim -1) ;
$frm .= "\n\$x\n.\n" ;
eval $frm ;

while( <STDIN> ){       # read col names
    #if( /^\s*#/ ){ print ; next ; }         # comment 
    last ; }
chop ;
$_ =~ s/\001//g;		    # remove SOH markers
@H = split( /\t/, $_ ) ;            # column names
$z = 13 ;   # default size for printf of list format
for (@H){ $z = length($_) if length($_) > $z ; } # get longest
$con1 = "%$z" . "s | " ; # printf control stg
$HH = $#H ;
for (1..10){ push( @H, "-DATA-ERROR-" ) ; }
while(<STDIN>){         # the data & definitions
    $j++;
    if( $j < 1 ) { next ; }	# Skip header. Carlo.
    &conv ; }
sub conv {          # convert, output the record
    print "\n" ;        # blank line separates each record
    chop ;
    @F = split( /\t/, $_ ) ;
    for( $i=0 ; $i <= $HH || $i <= $#F ; $i++ ){
    printf( $con1, $H[$i] ) ;
    $F[$i] =~ s/\\n/\n/g;		# Handle NoSQL escapes.
    $F[$i] =~ s/\\t/\t/g;
    if( length($F[$i]) <= $lim ){
        print $F[$i], "\n" ; }
    else{
        $init = 0 ;
        $x = $F[$i] ;
        do {
        print "\t\t" if $init++ ;
        write ;
        } while( $x ) ;
    }
    }
}

#
# End of program.
#
