#!/bin/bash

Renameplots=true
Rfile=$1
Date=""

if  [[ $1 = "-d" ]]; then
 Date=`date '+%Y%m%d_%H%M%S_'`
 Rfile=$2
fi

Rfname="${Rfile%.*}"

Rscript -e "options(warn=1); source(\"$Rfile\", echo=TRUE, keep.source=TRUE, max.deparse.length=Inf)" 2>&1 | tee "$Date$Rfname"_rresults.txt
RET=${PIPESTATUS[0]}

# to join multiple PDFs, pdftk required
if [ -x "$(command -v pdftk)" ]; then
if [[ $Renameplots && -f Rplots1.pdf ]]; then
 pdftk Rplots*.pdf cat output tmp.pdf
 rm -f Rplots*.pdf
 mv -f tmp.pdf Rplots.pdf
fi
fi

if [[ $Renameplots && -f Rplots.pdf ]]; then
 mv Rplots.pdf "$Date$Rfname"_rplots.pdf
fi

exit $RET
