#!/bin/sh
# set -x

# initialize
doascii=false
doverbose=true
gz=cat

# process switches
while [ x"$1" != x ]; do
    case $1 in
	-a) doascii=true
	    shift
	    continue;;

	-c) gz="gzip -c"
	    shift
	    continue;;

	-f) doascii=false
	    shift
	    continue;;

	-l) doverbose=true
	    shift
	    continue;;

	-s) doverbose=false
	    shift
	    continue;;

	*)  break;;
    esac
done

# check for required arguments
if [ x"$2" = x ]; then
  echo "usage: $0 [switches] input_fits 'key1 ... keyn' [output]"
  echo "output file is set to root_key.idx for use with funtools processing"
  echo " "
  echo "experimental switches (don't use unless you know what you are doing):"
  echo "  -a        # ASCII output, ignore -c (default: FITS table)"
  echo "  -c        # compress output using gzip"
  echo "  -f        # FITS table output (default: FITS table)"
  echo "  -l        # long output, i.e. with key value(s) (default: long)"
  echo "  -s        # short output, i.e. no key value(s) (default: long)"
  echo " "
  echo "output file name can be specified but funtools will not find it"
  exit 1
fi

# required arguments
FILE=$1
KEYS=$2
if [ x"$3" != x ]; then
  IDX=$3
fi

# output index file name
if [ x"$IDX" = x ]; then
  IDX1=`basename $FILE | sed 's/\(.*\)\.[^.]*/\1/g'`
  if [ x"$IDX1" = x ]; then
    IDX1=$FILE
  fi
  IDX2=`echo $KEYS | sed 's/ /_/g'`
  IDX=${IDX1}_${IDX2}.idx
fi

# input and output rows
ROWS1="\$N $KEYS"
if [ $doverbose = true ]; then
  ROWS2="N $KEYS"
else
  ROWS2='N'
fi

# remove possible already existing columns named N
# sort on the key column and output an additional column N
# output only the key and N columns
if [ $doascii = true ]; then
  funtable $FILE stdout "-N" | \
  funtable -s "$KEYS" stdin stdout "$ROWS1" | \
  fundisp -T stdin'[1]' "$ROWS2" > $IDX
else
  funtable $FILE stdout "-N" | \
  funtable -s "$KEYS" stdin stdout "$ROWS1" | \
  funtable stdin'[1]' $IDX "$ROWS2"
fi
if [ x"$gz" != x"cat" ]; then
  gzip $IDX
  IDX=$IDX.gz
fi

if [ -s $IDX ]; then
  echo "Index file $IDX created for data file $FILE"
else
  echo "ERROR: Index file $IDX not created"
fi
