#!/bin/sh
#  Rd2dvi -- check man pages (*.Rd help files) by LaTeX..
#
# Example (in $R_HOME):
#    bin/Rd2dvi src/library/base/man/Normal
#    bin/Rd2dvi `grep -l 'KEYWORD(distr' src/library/base/man/* |sort|uniq`
#
Pwd=`dirname $0`

R_HOME=`R RHOME`

MANTEXDIR=${R_HOME}/doc/manual
D2L="R CMD Rdconv -t latex"
file_sed='s/[_$]/\\\\&/g'
# Quote the      ^^^^  "\" twice (-> 4 \ ) since it used in ".."
## If perl-sh: sub subject() {
##	"$1"'{\\Large \\file{'`echo  $2  | sed $file_sed`"}$3" }
#
call_dir=`pwd`
if [ -f Rd2.tex ]
then
    echo "'Rd2.tex' already exists -- renaming it to  Rd2.tex.Older"
    echo " -------- "
    mv Rd2.tex Rd2.tex.Older
fi
touch Rd2.tex
if [ $# -eq 1  -a  -d $1 ]
then
    dir=$1
    test -d $dir/man && dir=$dir/man
    echo "Rd2dvi : \`Rdconv -t latex' $dir/ files..."
    files="${dir}/*.Rd"
    subj='of all in {\\Large \\file{'`echo $dir | sed $file_sed`'}}'
    # DBG: echo "files = $files"
    toc_sed='; s/\\input{Rd/\\Rdcontents{\\R\\ objects documented:} &/'
else
    files="$@"
    if [ $# -gt 1 ]; then subj=' ...etc '; else subj=''; fi
    subj='of {\\Large \\file{'`echo  $1  | sed $file_sed`"}$subj}"
    echo "Rd2dvi : Collecting files and \`Rdconv -t latex'ing them ..."
    toc_sed=''
fi
## DBG: echo ''; echo 'subj:'; echo "$subj"; echo ''
for f in $files
do
    echo $f
    $D2L $f >> Rd2.tex
done
echo "MANTEXDIR='$MANTEXDIR'"
R_P=`echo 'getenv("R_PAPERSIZE")'| R --vanilla --quiet|grep -v getenv|grep '"'|sed 's/ *//g;s/"//g'`
sed "s/a4paper/${R_P}paper/; s| documentation |& ${subj} |; ${toc_sed}" \
  ${MANTEXDIR}/Rd2dvi.tex > Rd2dvi.tex
if [ ! -f Rd.sty ]; then
 sed 's/markright{#1}/markboth{#1}{#1}/' ${MANTEXDIR}/Rd.sty > Rd2.sty
fi
#exit
#---------------------
latex Rd2dvi
if [ -x `/usr/bin/which makeindex` ]
then makeindex Rd2dvi
     latex Rd2dvi
fi
if [ -x `/usr/bin/which xdvi` ]
then  xdvi Rd2dvi &
fi
echo ''
echo 'Rd2dvi: You may want to clean up by'
echo '    rm -f Rd2dvi.* Rd2.sty Rd2.tex*'
echo ''
