/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *  Evaluation of R expressions.
 *
 *  $Id: R_eval.c,v 1.7 2004/02/17 18:48:27 warnes Exp $
 *
 */

#include <RPy.h>

/* The Python original SIGINT handler */
PyOS_sighandler_t python_sigint;

/* Indicates whether the R interpreter was interrupted by a SIGINT */
int interrupted = 0;

/* Abort the current R computation due to a SIGINT */
void interrupt_R(int signum)
{
  interrupted = 1;
  error("Interrupted");
}


/* Evaluate a SEXP. It must be constructed by hand. It raises a Python
   exception if an error ocurred in the evaluation */
SEXP do_eval_expr(SEXP e) {
  SEXP res;
  int error = 0;
  PyOS_sighandler_t old_int;

  /* Enable our handler for SIGINT inside the R
     interpreter. Otherwise, we cannot stop R calculations, since
     SIGINT is only processed between Python bytecodes. Also, save the
     Python SIGINT handler because it is necessary to temporally
     restore it in user defined I/O Python functions. */
  stop_events();

  #ifdef _WIN32
    old_int = PyOS_getsig(SIGBREAK);
  #else
    old_int = PyOS_getsig(SIGINT);
  #endif
  python_sigint = old_int;

  signal(SIGINT, interrupt_R);

  interrupted = 0;
  res = R_tryEval(e, R_GlobalEnv, &error);

  #ifdef _WIN32
    PyOS_setsig(SIGBREAK, old_int);   
  #else 
    PyOS_setsig(SIGINT, old_int);
  #endif

  start_events();

  if (error) {
    if (interrupted) {
      PyErr_SetNone(PyExc_KeyboardInterrupt);
    }
    else
      PyErr_SetString(RPyExc_Exception, get_last_error_msg());
    return NULL;
  }


  return res;
}

/* Evaluate a function given by a name (without arguments) */
SEXP do_eval_fun(char *name) {
  SEXP exp, fun, res;

  fun = get_from_name(name);
  if (!fun)
    return NULL;

  PROTECT(fun);
  PROTECT(exp = allocVector(LANGSXP, 1));
  SETCAR(exp, fun);

  PROTECT(res = do_eval_expr(exp));
  UNPROTECT(3);
  return res;
}

/*
 * Get an R object from his name. When not found, an exception is
 * raised. The checking of the length of the identifier is needed to
 * avoid that R raises an error. If this happens, Python dumps core.
 */
SEXP get_from_name(char *ident) {
  SEXP obj;

  /* For R not to throw an error, we must check the identifier is
     neither null nor greater than MAXIDSIZE */
  if (!*ident) {
    PyErr_SetString(RPyExc_Exception, "attempt to use zero-length variable name");
    return NULL;
  }
  if (strlen(ident) > MAXIDSIZE) {
    PyErr_SetString(RPyExc_Exception, "symbol print-name too long");
    return NULL;
  }

  obj = Rf_findVar(Rf_install(ident), R_GlobalEnv);
  if (obj == R_UnboundValue) {
    PyErr_Format(RPyExc_Exception, "Object \"%s\" not found", ident);
    return NULL;
  }
  return obj;
}

/* Obtain the text of the last R error message */
char *get_last_error_msg() {
  SEXP msg;

  msg = do_eval_fun("geterrmessage");
  return CHARACTER_VALUE(msg);
}


syntax highlighted by Code2HTML, v. 0.9.1