#!/usr/bin/env sh

#
# A small helper sh script to compile R Noweb file using knitr.
#

usage()
{
cat << EOF
Usage: $0 [-cxlq] file

This script weaves an Rnw file using knitr.

OPTIONS:
   -h      show this message
   -c      clean temp file (generated from *tex programs)
   -x      postprocess with xelatex
   -l      postprocess with latex
   -q      quiet (do not display R console output)
EOF
}

LOGFILE=result.log
ERRFILE=error.log
exec 3>$LOGFILE
exec 4>$ERRFILE

CLEAN=
TEX=
XETEX=
QUIET=
while getopts "h:cxlq" OPTION
do
    case $OPTION in
	h)
	    usage
	    exit 1
	    ;;
	c)
	    CLEAN=1
	    ;;
	x)
	    XETEX=1
	    ;;
	l)
	    TEX=1
	    ;;
	q)
	    QUIET=1
	    ;;
	?)
	    usage
	    exit
	    ;;
    esac
done
shift $(($OPTIND-1))

if [ -r "$1" ]; then
    echo "Processing $*"
    if [[ $QUIET = 1 ]]; then
	(
	    R --no-save --no-restore -e "require(knitr); knit('$*')"
	) 1>&3 2>&4
	echo "Check the *.log generated files for more information."
    else
	R --no-save --no-restore -e "require(knitr); knit('$*')"
    fi
    if [[ $XETEX = 1 ]]; then
	xelatex ${*%%.Rnw}.tex
	if [[ $CLEAN = 1 ]]; then
	    rm *.aux
	fi
    fi
    if [[ $TEX = 1 ]]; then
	pdflatex ${*%%.Rnw}.tex
    fi

    exit 1
else
    echo "Can't read input file."
    exit 0
fi
#
