#!/bin/sh
#
# Truncates the column data to make them fit into the 
# field width specification.
#

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.
    -b    Strips extra blanks from field edges.
    -n    Strips table header from output.

Truncates any data column wider than the length specified by the column
definition header line.

This operator reads an rdbtable from a file and prints the output rdbtable
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
        ;;
    -b)    shift; strip_blanks=1      ;;
    -n)    shift; no_hdr=1      ;;
    *)     break     ;;
  esac
done

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

awk 'BEGIN { NULL=""; FS="\t"; OFS=FS; }
# Table comments.
r == 0 && $0 ~ /^ *#/ { if( ! '${no_hdr:-0}' ) print; next; }
# Column names.
r == 0 { if( ! '${no_hdr:-0}' ) print; r++; next; }
# Column definitions.
r == 1 {
  split( $0, c_len )
  while( c_len[++c] != NULL ) {
	c_len[c] = substr( c_len[c], 1, index( c_len[c], " " ))
	gsub( /[^0-9]+/, NULL, c_len[c] )
  }
  if( ! '${no_hdr:-0}' ) print; r++; next;
}
{
  c=1
  if( '${strip_blanks:-0}' ) {
	sub( /^ */, NULL, $1 )
	sub( / *$/, NULL, $1 )
  }
  out_rec = substr( $1, 1, c_len[c] )
  while( ++c <= NF ) {
	if( '${strip_blanks:-0}' ) {
	  sub( /^ */, NULL, $c )
	  sub( / *$/, NULL, $c )
	}
	out_rec = out_rec OFS substr( $c, 1, c_len[c] )
  }
  print out_rec
}' ${1}

exit $?

