#!/bin/sh
#
# Prints various types of info taken from an rdbtable body.
#

RCS_ID='$Id$'

my_name=$(basename $0)

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

        NoSQL operator: ${my_name}

Usage:  ${my_name}  [options]  [rdbtable]

Options:
    -h    Print this help info.
    -H F  Write table header to file 'F'. Warning: ${my_name} does
          not do any locking on that file, so make sure you pick a
          unique name for it. A safe bet is suffixing the name with
          your shell process-id (\$\$), as usual. If the file already
		  exists, ${my_name} prints an error message and exits.
    -t X  Type of information requested. 'X' can be one of:

          n : Print only the No. data rows in the input table.

Prints various pieces of data, extracted from the body of an rdbtable.
Default is to print the whole table body to STDOUT.

This operator reads an rdbtable from a file and prints the requested info
to STDOUT. If no rdbtable is specified on the command line, then the input
table is read from STDIN.

$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
        ;;
    -t)    shift; info_type=$1; shift ;;
    -H)    shift; hdr_file=$1; shift  ;;
    *)     break     ;;
  esac
done

# Check for correctness of command line arguments.

case ${1} in
  -*)
    echo "Usage: ${my_name} [options] [rdbtable]" >&2
    exit 1
    ;;
esac

case ${hdr_file} in
  -*)
    echo "Usage: ${my_name} [options] [rdbtable]" >&2
    exit 2
    ;;
esac

case ${info_type} in
  n)	count_only=1    ;;
  -*)
	echo "Usage: ${my_name} [options] [rdbtable]" >&2
	exit 3
	;;
esac

# It is mandatory that the header file does not exist yet. Just think
# what would happen if we specified '-H' followed by the actual input
# table name: the table would be overwritten by its header !!!
if [ -s "${hdr_file}" ]
then
  echo "Header file ${hdr_file} exists. Cannot continue" >&2
  exit 4
fi

awk 'BEGIN { NULL=""; FS="\t"; OFS=FS; }
# Table comments.
r==0 && $0 ~ /^ *#/ {
  if( "'"${hdr_file}"'" != NULL ) print > "'"${hdr_file}"'"
  next
}
# Column names.
r==0 { 
  if( "'"${hdr_file}"'" != NULL ) print > "'"${hdr_file}"'"
  r++; next;
}
# Column definitions.
r == 1 { NR=0;
  if( "'"${hdr_file}"'" != NULL ) print > "'"${hdr_file}"'"
  r++; next;
}
'${count_only:-0}' == 0 { print }
END { if('${count_only:-0}') print NR }' ${1}

exit $?

