#!/bin/sh

##
# Convert Rd files to latex and make them available for inclusion in 
# some other tex file (e.g. package manual)
# 
# Usage:  If you have an Rd file called "xxx.Rd" then in your manual use
# /include{xxx}
#
#
# 


R_CMD="R";

# Work around for HMDC servers
if [ -x "/usr/bin/R" ]; then
    R_CMD="/usr/bin/R";
fi


# create a directory where latex files will take place

#if [ ! -d Rd ]
#then
#    mkdir Rd
#    cp /usr/share/R/texmf/Rd.sty Rd
#    cp /usr/share/R/texmf/upquote.sty Rd
#    cp /usr/share/R/texmf/upquote.sty .
#fi

${R_CMD} CMD BATCH copyRd

Rdfiles=`ls ../../man/*.Rd`
for rd in ${Rdfiles}
  do
    newname=`basename ${rd} .Rd`
    ${R_CMD} CMD Rdconv -t=latex ${rd} -o Rd/${newname}.tex
  
    ### basically replace "HeaderA" with "section*" 
    perl -i -pe 's#HeaderA{(.*)}{(.*)}{(.*)}#subsection{{\\tt \1}: \2}\\label{ss:\3}#i' Rd/${newname}.tex 

done

# we can use this code to quick-update the popups
#perl -i -pe 's/test1/this is some text/ig' ../../R/ameliagui.R

## Sweave should have already been run by R CMD build
#echo "Sweave(\"cem.Rnw\")" | ${R_CMD} --slave
#echo "library(\"utils\"); options(\"width\"=80); Sweave(\"amelia-vign.Rnw\")"  | ${R_CMD} --no-save --no-restore 
#if [ $? -ne 0 ]
#then
#	echo "Error in Sweave: $!";
#	exit 1;
#fi

#create the manual
pdflatex amelia
bibtex amelia
pdflatex amelia
pdflatex amelia
pdflatex amelia
pdflatex amelia

## report errors:
grep Warning amelia.log
grep "I'm skipping" amelia.blg
grep Warning amelia.blg
grep -i Error amelia.blg

## cleanup
rm -f *.aux *.toc *.log *.out *.blg *.bbl
rm -f amelia-*.pdf
rm -f amelia-*.eps
rm -f comp*
rm -f Rplots.pdf
rm -f varopts.* tscs.* step*.* rangepri.* priors.* obsprior.*
rm -f distpri.* diag.* obspri.*
rm -f amelia.tex a007.tex

## rm figures
rm -f disp-2d-good.* disperse-bad.* disperse-good.* overdis1d.* overdis2d.* overimp.* 

rm -rf Rd
