#!/bin/csh
# This is "cgihtml", which is used to convert cgiwrite output to
# comma separated values (csv) format using cgiread in R, and then
# to make an html page with the data as a table in the middle.
# The required arguments are the cgiwrite output file name,
# the name of the file to be produced (or overwritten), and the
# name of a template html file containing a line with just "TABLE"
# where the table goes.

# Check for arguments
if ( $# != 3 ) then
  echo Usage: cgihtml dbName htmlOutName htmlInName
  exit
endif

# check files exist
if (! -e $1) then
  echo $1 does not exist
  exit
endif
if (-s $1 == 0) then
  echo $1 is empty
  exit
endif
echo $1 > cgireadDBfile.tmp

echo $2 > cgihtmlOutfile.tmp

if (! -e $3) then
  echo $3 does not exist
  exit
endif
if (-s $3 == 0) then
  echo $3 is empty
  exit
endif
echo $3 > cgihtmlInfile.tmp

########## Part 1: db to *.csv ###########

# erase log file if it exists, then run R program
if (-e cgireadlog.tmp) then
  rm -f cgireadlog.tmp
endif
set tmpfile = `mktemp -u /tmp/cgiwrite.XXXXXX`
R --no-restore --no-save --no-readline < cgiread.R >& $tmpfile


if (-e cgireadlog.tmp) then
  cat cgireadlog.tmp
  rm -f cgireadlog.tmp
  rm -f $tmpfile
endif
else
  echo Sorry, something went wrong!
  cat $tmpfile
  if (-e $tmpfile) then
    rm -f $tmpfile
  endif
  if (-e cgireadDBfile.tmp) then
    rm -f cgireadDBfile.tmp
  endif
  if (-e cgihtmlInfile.tmp) then
    rm -f cgihtmlInfile.tmp
  endif
  if (-e cgihtmlOutfile.tmp) then
    rm -f cgihtmlOutfile.tmp
  endif
  exit
endif

########## Part 2: csv  to html ###########
# erase log file if it exists, then run R program
if (-e cgihtmllog.tmp) then
  rm -f cgihtmllog.tmp
endif
set tmpfile = `mktemp -u /tmp/cgihtml.XXXXXX`
R --no-restore --no-save --no-readline < cgihtml.R >& $tmpfile

if (-e cgireadDBfile.tmp) then
  rm -f cgireadDBfile.tmp
  rm -f $tmpfile
endif


if (-e cgihtmllog.tmp) then
  cat cgihtmllog.tmp
  rm -f cgihtmllog.tmp
else
  if (-e $tmpfile) then
    rm -f $tmpfile
  endif
  echo Sorry, something went wrong!
endif

if (-e cgireadDBfile.tmp) then
  rm -f cgireadDBfile.tmp
endif
if (-e cgihtmlInfile.tmp) then
  rm -f cgihtmlInfile.tmp
endif
if (-e cgihtmlOutfile.tmp) then
  rm -f cgihtmlOutfile.tmp
endif
