#****************************************************************************
#  ##   ##         #####   #####  ##     **       NoSQL RDBMS - rename      *
#  ###  ##        ####### ####### ##     **        $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.                                *
#****************************************************************************
#
#  Rename a table column.
#
#  Renames a specified column. This operator takes exactly two arguments:
#  'oldname' and 'newname'. If more arguments are specified, they are
#  silently disregarded. 
#
#  If neither 'oldname' nor 'newname' are specified, then the input table
#  is simply print to STDOUT unchanged. The same applies if only one name
#  is specified.
#
#  This NoSQL operator reads a table from STDIN and writes an
#  table to STDOUT.
#
########################################################################

########################################################################
# BEGIN block
########################################################################

BEGIN \
{
  NULL = ""; FS = OFS = "\t";
  if ( split( __nosql_args, old_new, " " ) < 2 ) delete old_new[1]
}

########################################################################
# Main loop
########################################################################

NR == 1 \
{
  # Load the column position array.
  while ( ++p <= NF ) { P[$p] = p; N[p] = $p; }

  # Now rename 'oldname' to 'newname' in the header.
  for ( i in N )
  {
	if ( N[i] == old_new[1] ) N[i] = old_new[2]
  }

  while ( N[++j] != NULL ) out_rec = out_rec OFS N[j]

  # Remove leading extra OFS from out_rec, then print header and dashline.
  sub( /^\t/, "", out_rec ); print out_rec
  gsub( /[^\t]/, "-", out_rec ); print out_rec
}

# Dashline.
NR == 2 { next }

# Table body.
NR > 2 { print }

