#!/bin/bash

# This script is depreciated in favor of pgfsweave-script.R which 
# is easier to maintain. There have been changes in pgfSweave-script.R which 
# are not mirrored here, so really you should not use this script at all.

revision='$Id$'
version="pgfSweave package ${revision}"

usage="Usage: pgfSweave [options] file

A simple front-end for pgfSweave()

Options:
  -h, --help                print short help message and exit
  -v, --version             print pgfSweave version info and exit
  -p, --pdf                 use texi2dvi option pdf=T or call pdflatex 
                            (defalt is latex)
  -s, --pgfsweave-only      dont compile to pdf/dvi, only run Sweave
  -n, --graphics-only       dont use the texi2dvi() funciton in R, compile 
                            graphics only ; ignored if --pgfsweave-only is
                            used

Package repository: 
http://github.com/cameronbracken/pgfSweave (scm)
http://r-forge.r-project.org/projects/pgfsweave/ (for precompiled packages)
"

pdf=FALSE
quiet=FALSE
compiletex=TRUE
graphicsonly=FALSE
R_EXE=`which R`
#R_EXE="${R_HOME}/bin/R"

while true
do
  case $# in 0) break ;; esac
  case $1 in
    -q|--quiet) quiet=TRUE;shift;;
    -p|--pdf) pdf=TRUE;shift;;
    -s|--pgfsweave-only) compiletex=FALSE;shift;;
    -v|--version) echo "${version}"; exit 0 ;;
    -h|--help) echo "${usage}"; exit 0 ;;
    -n|--graphics-only) graphicsonly=TRUE;shift;;
    -|--) shift; break;;
    -*) echo "pgfSweave: Unknown or ambiguous option \`$1'." >&2
        echo "pgfSweave: Try \`--help' for more information." >&2
        exit 1;; 
     *) break ;;
  esac
done

case $# in
 0)
  echo "pgfSweave: No Input Files." >&2
  echo "pgfSweave: Try \`--help' for more information." >&2
  exit 2;;
 1) ;;
esac

    # In the first case run through pgfSweave but no not compile document or 
    # graphics from within R. Instead, run the shell script generated by 
    # pgfSweave() externally to compile the graphics
if [[ "$graphicsonly" == "TRUE" ]]; then
    echo "library(\"pgfSweave\");
          pgfSweave(\"$1\",pdf=$pdf,quiet=$quiet,compile.tex=FALSE)" | \
                                            "${R_EXE}" --no-restore --slave
                                    
    sh "${1%.*}.sh"
    
    # In this case, just make a call to the R function pgfSweave() with the
    # options intact.
else
    echo "library(\"pgfSweave\");
          pgfSweave(\"$1\",pdf=$pdf,quiet=$quiet,compile.tex=$compiletex)" | \
                                            "${R_EXE}" --no-restore --slave
fi


