#!/bin/bash

. zdb_constants

if [ "$#" -lt "2" ]; then
  echo "USAGE: `basename ${0}` table col1 [col2 .. coln]"
  exit 1
fi

TABLE_ATTR=${ZDB_DIR}/${1}.def
TABLE_DATA=${ZDB_DIR}/${1}.dat

if [ ! -e "${TABLE_ATTR}" ]; then
   echo "Error, table ${1} is undefined"
   exit 1
fi

if [ ! -e "${TABLE_DATA}" ]; then
   echo "Error, table ${1} contains no data"
   exit 1
fi

shift

field_list=""
error_flag=""

for attr in ${@}
do
   grep "^${attr}$" ${TABLE_ATTR} > /dev/null 2>&1

   if [ "$?" -ne "0" ]; then
      echo "Error, column ${attr} does not exist"
      error_flag="true"
   fi

   field=$( grep -n "^${attr}$" ${TABLE_ATTR} | awk -F':' '{print $1}' )

   if [ -z "${field_list}" ]; then
      field_list="${field}"
   else
      field_list="${field_list},${field}"
   fi

done

if [ ! -z "${error_flag}" ]; then
   exit 1
fi


#cut -d':' -f $field_list ${TABLE_DATA} | tr ':' '\t'
while read line
do
   for f in $( echo $field_list | tr ',' ' ' )
   do
      output=$( echo $line | awk -F':' -v field=$f '{print $field}' )
      echo -e "$output\t\c"
   done
  echo ""
done < ${TABLE_DATA}

exit 0


# Generated with sh2html - freely available from http://www.zazzybob.com/sh2html.html