#****************************************************************************
#  ##   ##         #####   #####  ##     **       NoSQL RDBMS - soundex     *
#  ###  ##        ####### ####### ##     **      $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.                                *
#****************************************************************************
#
# Compute the soundex codes for a table column.
#
##########################################################################
#
# Usage: nosql soundex [-n|--name name ] column < table 
#
# Takes a NoSQL table and prints the soundex code associated with each
# data value in a specified column.
# 
# This operator reads a table from STDIN and prints a new table to STDOUT.
# The output table is the input table with an added leading column (the
# 'soundex' column). The new column contains the soundex code of the data
# in 'column'. The new column name is the same as 'column', with an "s"
# prepended to it, or the name specified with option '-n' if present.
# For instance, if the requested column is 'Name', then  the computed
# soundex column default name will be 'sName'.
# 
##########################################################################

Exit ()
{
  rm -f "${traplist}"
  exit $1
}

# Include main NoSQL front-end.
. ${NSQLIB}/sh/nosqlmain

while [ $# -ge 1 ]
do
  case $1 in
    -n|--name)  shift; col_name=$1 ;;
    *)     	    s_column=$1; break ;;
  esac
  shift
done

# Check for required command line arguments.

if test -z "${s_column}"
then
  echo "nosql soundex: usage: nosql soundex [-n|--name name ] column" >&2
  Exit 1
fi

test -z "${col_name}" && col_name="s${s_column}"

tmp1=$(${NSQTEMPF})
tmp2=$(${NSQTEMPF})

traplist="${tmp1} ${tmp2}"
trap "rm -f ${traplist}" 0 1 2 15

tee ${tmp1} | nosql column ${s_column} |
  ${NSQLIB}/bin/soundex > ${tmp2}

${NSQAWK} 'BEGIN { NULL = ""; FS = OFS = "\t"; }

# Column names.
NR == 1 { col_names = "'"${col_name}"'" OFS $0; print col_names }

# Dashline.
NR == 2 { gsub( /[^\t]/, "-", col_names ); print col_names }

NR > 2 \
{
  getline soundex < "'"${tmp2}"'"
  print soundex, $0
}' ${tmp1}

Exit $?

