#!/bin/bash
#--------------------------------------------------------------------------
# What: Run Sweave and LaTeX directly from command line
# $Id: Sweave.sh,v 1.4 2005/02/23 07:20:55 ggorjan Exp $
#=======================================================
# MINIMALLY MODIFIED by Shravan Vasishth (line 167 below)
# Note that this script requires that the library weaver 
# (along with digest, and codetools) is installed. 
# 2007/01/05
#=======================================================
#--------------------------------------------------------------------------
# Needed:
#  - R http://www.r-project.com
#  - texi2dvi ??
#  - rubber is optional http://rubber.sourceforge.net
#--------------------------------------------------------------------------
# Initial idea taken from:
# http://www.ci.tuwien.ac.at/~leisch/Sweave/FAQ.html#x1-5000A.3
# E.g., for writing makefiles it can be useful to run Sweave directly from
# a shell rather than manually start R and then run Sweave. This can easily
# be done using a simple shell script
#--------------------------------------------------------------------------

# Nothing to configure below!
#---------------------------------------------------------------------------

NAME=$(basename $0)

# Usage: usage
# Print the usage.
usage () {
    cat <<EOF
NAME
    $NAME - Run Sweave and LaTeX directly from command line

SYNOPSIS
    $NAME [OPTION] ...

DESCRIPTION
    Run Sweave directly from command line with given options and optionally
    also LaTeX. Following options can be used:

    -h, --help
      Print this output.

    -l, --latex
      Run LaTeX on prepaired file by Sweave. Look under details for set
      of LaTeX commands etc. By default, both postscript and PDF are
      created. Use options -p or -d to create only one of them.

    -p, --ps
      Create postscript in LaTeX run. Automatically implies option -l.

    -d, --pdf
      Create PDF in LaTeX run. Automatically implies option -l.

    -nr, --no-rubber
      Don't use 'rubber'. This is default if rubber is not found. This
      option might be usefull in case of problems with 'rubber' or if you
      just want to use LaTeX directly.

    -m, --mode
      Direct mode might be usefull for multiple input files. By default all
      input files are first processed with Sweave and then all by LaTeX.
      With this option each file is processed with Sweave and directly
      after that with LaTeX and nex file with Sweave and ... There is no
      difference for only one input file.

DETAILS
    R is launched with following options:
     - don't save it i.e. --no-save
     - don't restore anything i.e. --no-restore

    LaTeX in the context means either:
     - rubber 'http://rubber.sourceforge.net/' if it is found, otherwise
     - texi2dvi if it is found, otherwise
     - hardoced set of LaTeX and friends is used (look bellow), where latex
       can be pure latex of pdflatex. There may appear some errors on
       screen if there is no need for bibtex and/or makeindex, since these
       two are also on the list.

       The list of commands is:
        latex
        bibtex
        makeindex
        latex
        latex

EXAMPLE
    Process only with Sweave
    $NAME Sweave-test-1.Rnw

    Create both postscript and PDF
    $NAME -l Sweave-test-1.Rnw

    Create only PDF
    $NAME -d Sweave-test-1.Rnw

    Create only PDF with direct mode
    $NAME -d -m Sweave-test-1.Rnw

AUTHOR
    Gregor GORJANC <gregor.gorjanc at bfro.uni-lj.si>

EOF
}

# Get options
OPTIONS=$@
for OPTION in $@; do
    case "$OPTION" in
        -h | --help )
        usage
        exit 0
        ;;
        -l | --latex )
        LATEX=yes
        OPTIONS=$(echo $OPTIONS | sed -e "s/--latex//" -e "s/-l//")
        OPTIONS_ECHO="$OPTIONS_ECHO - use LaTeX and friends after Sweave\n"
        ;;
        -p | --ps )
        LATEX=yes
        PS=yes
        OPTIONS=$(echo $OPTIONS | sed -e "s/--ps//" -e "s/-p//")
        OPTIONS_ECHO="$OPTIONS_ECHO - use LaTeX and friends after Sweave\n"
        OPTIONS_ECHO="$OPTIONS_ECHO - create PS\n"
        ;;
        -d | --pdf )
        LATEX=yes
        PDF=yes
        OPTIONS=$(echo $OPTIONS | sed -e "s/--pdf//" -e "s/-d//")
        OPTIONS_ECHO="$OPTIONS_ECHO - create PDF\n"
        ;;
        -nr | --no-rubber )
        RUBBER=no
        OPTIONS=$(echo $OPTIONS | sed -e "s/--no-rubber//" -e "s/-nr//")
        OPTIONS_ECHO="$OPTIONS_ECHO - ??\n"
        ;;
        -m | --mode )
        MODE=yes
        OPTIONS=$(echo $OPTIONS | sed -e "s/--mode//" -e "s/-m//")
        OPTIONS_ECHO="$OPTIONS_ECHO - direct mode\n"
        ;;
        * )
        ;;
    esac
done

# Defaults for R
ROPTIONS="--no-save --no-restore"

# Defaults for LaTeX
if [ "$LATEX" = "yes" -a ! -n "$PS" -a ! -n "$PDF" ]; then
    PS=yes
    PDF=yes
fi

# File list
FILES=$OPTIONS

# Print usage if there is no input files
if [ ! -n "$FILES" ]; then
    echo -e "\nError: There is no input files! Usage is:\n"
    usage
    exit 1
fi

# Functions
# --- The R machine ---
sweave_R ()
{
    echo "library(weaver); Sweave(\"$1\",driver=weaver())" | R $ROPTIONS
}

# --- The LaTeX machine ---
sweave_latex ()
{
    # Strip of .Rnw or .Snw from filename
    FILE=$(echo $1 | sed -e 's/\.Rnw//' -e 's/\.Snw//')

    # Rubber
    if [ `which rubber` -o "$RUBBER" != "no" ]; then
        echo -e " - using 'rubber'"
        if [ "$PS" = "yes" ]; then
            echo -e "\nPostscript creation"
            rubber -p $FILE
        fi
        if [ "$PDF" = "yes" ]; then
            echo -e "\nPDF creation"
            rubber -d $FILE
        fi
    # texi2dvi
    elif [ `which texi2dvi` ]; then
        echo -e " - using 'tex2dvi'"
        if [ "$PS" = "yes" ]; then
            echo -e "\nPostscript creation"
            texi2dvi --clean --quiet $FILE
            dvips ${FILE}.dvi -o ${FILE}.ps
        fi
        if [ "$PDF" = "yes" ]; then
            echo -e "\nPDF creation"
            texi2dvi --clean --quiet --pdf $FILE
        fi
    else
        echo -e " - using hardcoded list of 'LaTeX and friends' commands"
        if [ "$PS" = "yes" ]; then
            echo -e "\nPostscript creation"
            latex $FILE
            bibtex $FILE
            makeindex $FILE
            latex $FILE
            latex $FILE
            dvips ${FILE}.dvi -o ${FILE}.ps
        fi
        if [ "$PDF" = "yes" ]; then
            echo -e "\nPDF creation"
            pdflatex $FILE
            bibtex $FILE
            makeindex $FILE
            pdflatex $FILE
            pdflatex $FILE
        fi
    fi
}

# Title
echo -e "\nSweave directly from command line ..."

# Report options
echo -e " - R options are: $ROPTIONS"
echo -e "$OPTIONS_ECHO"


# Main program
for FILE in $FILES; do
    sweave_R $FILE
    if [ "$LATEX" = "yes" -a "$MODE" = "yes" ]; then
        echo -e "\nLaTeX on produced tex files"
        sweave_latex $FILE
    fi
done

if [ "$LATEX" = "yes" ]; then
    echo -e "\nLaTeX on produced tex files"
    for FILE in $FILES; do
        sweave_latex $FILE
    done
else
    exit 0
fi

# Exit
exit 0

#--------------------------------------------------------------------------
# Sweave.sh ends here
