#!/bin/sh

flag="none"

while [ $# -gt 0 ]
do
  case "$1" in
    -strict )
      flag="strict"
      shift
      ;;
    -mixed )
      flag="mixed"
      shift
      ;;
    -path )
      shift
      ;;
    -* )
      exec >&2
      echo "$0: Unrecognized option $1"
      exit 1
      ;;
    * )
      break
      ;;
  esac
done

if [ "$#" -gt 0 ]
then
  argument="$1"
  target=$(cd "$argument" && pwd)
  target=${target%/}
  case "$target" in
    */Archive ) ;;
    * ) target=$target/Archive ;;
  esac
else
  if [ -z "${EDIRECT_PUBMED_MASTER}" ]
  then
    echo "Must supply path to archive files or set EDIRECT_PUBMED_MASTER environment variable"
    exit 1
  else
    MASTER="${EDIRECT_PUBMED_MASTER}"
    MASTER=${MASTER%/}
    target="$MASTER/Archive"
  fi
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%/}

echo '<?xml version="1.0" encoding="UTF-8"?>'
echo '<!DOCTYPE PubmedArticleSet PUBLIC "-//NLM//DTD PubMedArticle, 1st June 2018//EN" "https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_180601.dtd">'
rchive -gzip -flag "$flag" -fetch "$target" \
  -head "<PubmedArticleSet>" -tail "</PubmedArticleSet>"
