#!/bin/sh
##--- NEW: ----------
##
## Given a list of files of the form    .../.../<name>.R,
##
## Produce one large file, i.e. write to  stdout
##  'cat'ting the files together with
##  1) Putting   a HEADER in front
##  2) Wrapping every file in order to be more order independent
##  3) appending a FOOTER ...

## Should work WHEREVER this is called from :
(cd `dirname $0`/..
 RHOME=`pwd`; export RHOME
)
RHOME=`cd ${RHOME}; pwd`	# absolute

PKG=$1; shift;
FILES="$@"

#Dbg> echo "RHOME=$RHOME"; echo
#Dbg> echo "FILES=$FILES"; echo ; echo; exit

## 1) ---- Header ----
(cat <<_EOF_
.ptime <- proc.time()
postscript('PKG-Examples.ps')
.par.postscript <- par(no.readonly = TRUE)
options(contrasts = c(unordered = "contr.treatment", ordered =  "contr.poly"))
_EOF_
) | sed "s/PKG/${PKG}/"
if [ "$PKG" != "base" ]; then echo "library('$PKG')" ; fi

## 2) ---- edit a few of these files:
for file in $FILES
do
 bf=`basename $file .R`
 if [ -n "`grep '_ Examples _' $file`" ]
 then
    echo '.Random.seed <- rep(7654,3); rm(list = ls())'
 else
    if [ "$USER" = maechler ];then
	## Remind certain people to upgrade the online help
	echo "'$bf' has no Examples.." >& 2
    fi
 fi

 cat $file

 if [ -n "`grep 'par(' $file`" ];then
    ## if there were 'par(..)' calls, now reset them:
    echo 'par(.par.postscript)'
 fi
done
## 3) ---- Footer ----
cat <<_EOF_
cat("Time elapsed: ", proc.time() - .ptime,"\n")
dev.off(); quit('no')
_EOF_
