#!/bin/sh

target=""
mode="query"
debug=false

while [ $# -gt 0 ]
do
  case "$1" in
    -h | -help | --help )
      mode=help
      break
      ;;
    -debug )
      debug=true
      shift
      ;;
    -path | -master )
      target=$2
      shift
      shift
      ;;
    -count )
      mode="count"
      shift
      ;;
    -counts )
      mode="counts"
      shift
      ;;
    -countr )
      mode="countr"
      shift
      ;;
    -countp )
      mode="countp"
      shift
      ;;
    -query | -phrase )
      mode="query"
      shift
      ;;
    -search )
      mode="search"
      shift
      ;;
    -exact )
      mode="exact"
      shift
      ;;
    -* )
      exec >&2
      echo "$0: Unrecognized option $1"
      exit 1
      ;;
    * )
      break
      ;;
  esac
done

if [ $mode = "help" ]
then
  cat <<EOF
USAGE: $0
       [-path path_to_pubmed_master]
       -count | -counts | -search | -exact | [-query]
       query arguments

EXAMPLE: phrase-search -query catabolite repress* AND protease inhibit*
EOF
  exit
fi

if [ -z "$target" ]
then
  if [ -z "${EDIRECT_PUBMED_MASTER}" ]
  then
    echo "Must supply path to postings files or set EDIRECT_PUBMED_MASTER environment variable"
    exit 1
  else
    MASTER="${EDIRECT_PUBMED_MASTER}"
    MASTER=${MASTER%/}
    target="$MASTER/Postings"
  fi
else
  argument="$target"
  target=$(cd "$argument" && pwd)
  target=${target%/}
  case "$target" in
    */Postings ) ;;
    * ) target=$target/Postings ;;
  esac
fi

osname=`uname -s | sed -e 's/_NT-.*$/_NT/; s/^MINGW[0-9]*/CYGWIN/'`
if [ "$osname" = "CYGWIN_NT" -a -x /bin/cygpath ]
then
  target=`cygpath -w "$target"`
fi

target=${target%/}

if [ "$debug" = true ]
then
  echo "mode: $mode, path: '$target', args: '$*'"
  exit
fi

case "$mode" in
   count )
     rchive -path "$target" -count "$*" 
     ;;
   counts )
     rchive -path "$target" -counts "$*" 
     ;;
   countr )
     rchive -path "$target" -countr "$*" 
     ;;
   countp )
     rchive -path "$target" -countp "$*" 
     ;;
   query )
     rchive -path "$target" -query "$*"
     ;;
   search )
     rchive -path "$target" -search "$*"
     ;;
   exact )
     rchive -path "$target" -exact "$*"
     ;;
esac
