#! /bin/sh

# This script constructs HTML views of PhotoML files

# Copyright © 2003-2010 Brendt Wohlberg <photoml@wohlberg.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License at
# http://www.gnu.org/licenses/gpl-2.0.txt.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.

# Most recent modification: 18 April 2010


pmlpath="`echo $0 | sed -e 's|/pmltrans||'`/.."
pmlvalidx="$pmlpath/tools/pmlvalid"

if [ ! "`which xsltproc 2>/dev/null`" ]; then
  echo "pmltrans: error executing xstlproc" >&2
  exit 1
fi

usage()
{
cat <<EOF >&2
usage: pmltrans [-h] [-f] [-s size] (([-e] [-m]) | [-d [-x]]) infile
       -h       Display usage information
       -f       Omit validity test
       -s size  Specify primary font size in points
       -e       Include exposure detail column when appropriate
       -m       Include location map when coordinates specified
       -d       Use detailed rather than summary output
       -x       Expand defaults before applying the XSL
EOF
}

fsparam=''
ecparam=''
lmparam=''
novalid=0
summary=1
expand=0
while [ $# -ge 1 ]; do
  case $1 in
    -s)    shift; fsparam="--stringparam font-size $1" ;;
    -f)    novalid=1 ;;
    -e)    ecparam="--stringparam disp-exposure 1" ;;
    -m)    lmparam="--stringparam disp-map 1" ;;
    -d)    summary=0 ;;
    -x)    expand=1 ;;
    -*)    usage; exit 1 ;;
    *)     infile=$1; break ;;
  esac
  shift
done   

if [ "$infile" = '' ]; then
  usage; exit 1
fi

if [ ! -f "$infile" -o ! -r "$infile" ]; then
  echo pmltrans: could not open file $infile >&2
  exit 1
fi

if [ $novalid -eq 0 ]; then
  if ! $pmlvalidx "$infile" 2>/dev/null; then
    echo pmltrans: validity error in file $infile >&2
    exit 2
  fi
fi

dtdpub=`grep DOCTYPE $infile | grep -o -e '-\/\/.*EN'`;
dtdtyp=`echo $dtdpub | grep -o -e '//DTD[^/]*//' | cut -d ' ' -f 2`
if [ "$dtdtyp" != 'PhotoML' ]; then
  echo "pmltrans: input document type $dtdtyp not recognised" >&2
  exit 3
fi

edxsl=$pmlpath/xsl/defaults/expand.xsl
if [ $summary -eq 0 ]; then
  xsl=$pmlpath/xsl/html/detailed.xsl
else
  expand=1
  xsl=$pmlpath/xsl/html/summary.xsl
fi

if [ -r /etc/xml/catalog -a "$XML_CATALOG_FILES" = '' ]; then
  XML_CATALOG_FILES=/etc/xml/catalog
fi
XML_CATALOG_FILES="$pmlpath/dtd/catalog.xml $XML_CATALOG_FILES"
export XML_CATALOG_FILES
unset SGML_CATALOG_FILES

tmpfile="/tmp/pmltrans.$$"
if [ $expand -eq 1 ]; then
  xsltproc $fsparam $ecparam $lmparam -o $tmpfile $edxsl $infile
  infile=$tmpfile
fi

xsltproc $fsparam $ecparam $lmparam $xsl $infile
status=$?

if [ -f "$tmpfile" ]; then
  rm -f $tmpfile
fi

exit $status
