#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <math.h>
#include <yafl_rnt.h>
#include "dbx_sign.h"
#include "dbx_ctrl.h"

/* this function is supposed to take place of the normal exception function */
/* called by floating point math routines for the various errors */
/* but this does not seem to work */
/* ??? */

/*
int matherr YPARAMS2(struct exception *,  x)
{
  emit_stdout("\007");
  crash(XCRASHED_FPE);
  return 0;
}
*/

/* this signal is generated in a number of cases depending on the */
/* system but mostly for division by zero */
static void handler_fpe YPARAMS2(int, sig)
{
  crash(XCRASHED_FPE);
}

/* this signal is generated by pressing the delete key */
/* beware as it can hang the system */
/* on the other hand it is already captured by the curses library */
static void handler_int YPARAMS2(int, sig)
{         
/* this handler must be reinstalled because the system resets it */
#ifdef SIGINT
  signal(SIGINT,handler_int); 
#endif  
  crash(XPRESSED_INT);
}

/* this should normally not happen */ 
static void handler_ill YPARAMS2(int,  sig)
{
  crash(XCRASHED_ILL);
}

static void handler_bus YPARAMS2(int,  sig)
{
#ifdef SIGBUS
  signal(SIGBUS,handler_bus); 
#endif  
  crash(XCRASHED_BUS);
}

static void handler_segv YPARAMS2(int,  sig)
{
#ifdef SIGSEGV
  signal(SIGSEGV,handler_segv); 
#endif  
  crash(XCRASHED_SEGV);
}

/* this is another keyboard-generated signal */
static void handler_tstp YPARAMS2(int,  sig)
{
/* this handler must be reinstalled because the system resets it */
#ifdef SIGTSTP
  signal(SIGTSTP,handler_tstp);
#endif  
  crash(XPRESSED_TSTP);
}

static void handler_abrt YPARAMS2(int,  sig)
{
/* this handler must be reinstalled because the system resets it */
#ifdef SIGABRT
  signal(SIGABRT,handler_abrt); 
#endif  
  crash(XCRASHED_ABRT);
}

static void handler_term YPARAMS2(int, sig)
{
  crash(XCRASHED_ABRT); /* ??? */
}


static void init_all_signals YPARAMS0
{
#ifdef SIGFPE
  signal(SIGFPE,handler_fpe);
#endif  
#ifdef SIGINT
  signal(SIGINT,handler_int);
#endif
#ifdef SIGILL  
  signal(SIGILL,handler_ill);
#endif
#ifdef SIGBUS  
  signal(SIGBUS,handler_bus);
#endif  
#ifdef SIGSEGV
  signal(SIGSEGV,handler_segv);
#endif  
#ifdef SIGTSTP
  signal(SIGTSTP,handler_tstp);
#endif
#ifdef SIGTERM  
  signal(SIGTERM, handler_term);
#endif
#ifdef SIGABRT  
  signal(SIGABRT,handler_abrt); 
#endif
#ifdef SIGTTIN  
  signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTTOU  
  signal(SIGTTOU, SIG_IGN);
#endif  
}

void init_dbx_sign YPARAMS0
{
  if (!envi_get_no_trap())
    init_all_signals();
}

void term_dbx_sign YPARAMS0
{
}

