#!/bin/sh
#
# Converts an /rdb list format to /rdb table format.
#
# Original code: starbase 2.24a , "listtotable"
#
# Adapted by Carlo Strozzi <carlos@linux.it>

RCS_ID='$Id: nsq-listtotable,v 0.9 1998/03/04 09:12:49 carlos Exp $'

my_name=$(basename $0)

while [ $# -ge 1 ] ; do
    case $1 in
		-h*) cat <<_EOH_

		NoSQL operator: ${my_name}

Usage:  ${my_name}  [options]  < input_file

Options:
	-h	Print this help info.

Converts an /rdb "list" to the corresponding /rdb "table" format.

This operator reads an /rdb "list" file via STDIN and produces
the corresponding /rdb table on STDOUT.

It is provided to help exchanging data between /rdb and NoSQL.

$RCS_ID

			----------------------
NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.
This program comes with ABSOLUTELY NO WARRANTY; for details
refer to the GNU General Public License.

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., 59 Temple Place Suite 330, Boston, MA 02111-1307
USA.
			----------------------

_EOH_
			exit 0
			;;
		*) break ;;
	esac
done

awk '
BEGIN {
	FS="	"

	ncol = 0
	getline
	while ( getline > 0 ) {
		if ( !length($0) ) break;

		ncol++
		N = $1
		C[ncol]  = N
		V[N] = $2
	}

	# print headline
	#
	for ( i = 1; i < ncol; i++ )
		printf "%s\t", C[i]
	print C[ncol]

	# print dashline
	#
	for ( i = 1; i < ncol; i++ ) {
		for ( j = length(C[i]); j--; )
			printf "-"
		printf "\t"
	}
	for ( j = length(C[ncol]); j--; )
		printf "-"
	print ""

	printvalues()
}

# Accumulate values
#
NF != 0 { X = 1; N = $1; V[N] = $2; next }

# Output and clear values
#
NF == 0 { if ( X ) printvalues(); X = 0  }
END 	{ if ( X ) printvalues(); X = 0	 }

function printvalues() {
	for ( i = 1; i < ncol; i++ ) {
		printf "%s\t", V[C[i]]
		V[C[i]] = ""
	}
	print V[C[ncol]]
	V[C[ncol]] = ""
}'
