#****************************************************************************
#  ##   ##         #####   #####  ##     **     NoSQL RDBMS - tabletolist   *
#  ###  ##        ####### ####### ##     **        $Revision: 2.1 $			*
#  #### ##        ###     ##   ## ##     ************************************
#  #######  ####  #####   ##   ## ##     **      Carlo Strozzi (c) 1998     *
#  ####### ######   ##### ## # ## ##     ************************************
#  ## #### ##  ##     ### ##  ### ##     **           Written by            *
#  ##  ### ###### ####### ######  ###### **          Carlo Strozzi          *
#  ##   ##  ####   #####   #### # ###### **     e-mail: carlos@linux.it     *
#****************************************************************************
#   NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.                          *
#   This program comes with ABSOLUTELY NO WARRANTY; for details             *
#   refer to the GNU General Public License.                                *
#****************************************************************************
#
#  Converts a table from 'table' to 'list' format.
#
#  This NoSQL operator reads a table from STDIN and writes a
#  'list' format of the same table to STDOUT.
#
##########################################################################

BEGIN \
{
	NULL = ""; FS = OFS = "\t"
	ncol = table_header( V, C, D )
	print NULL
}

{
	for ( i = 1; i <= ncol; i++ )
	{
		print C[i], $i
	}
	print NULL
}

END \
{
	# Handle empty input table.
	if ( NR < 3 )
	{
		for ( i = 1; i <= ncol; i++ )
		{
			print C[i]
		}
		print NULL
	}
}

function table_header( V, C, D,		header, dashes )
{
	getline	header
	getline	dashes
	if ( dashes !~ /(-+\t)*(-+)/ )
	{
	     do
		   {
			 header = dashes	
	       }
		 while ( getline dashes > 0 && dashes !~ /(-+\t)*(-+)/ )
	}

	n = split( header, C, /\t/ )
	n = split( dashes, D, /\t/ )

	return n
}

