#include <signal.h>
#include <errno.h>

sighandler_t _siguhandler[NSIG];

int _sigacthandler(int sig, int foo, unsigned int thread_context)
{
  unsigned int * foob;
  sighandler_t user_h;

  user_h = _siguhandler[sig];

#ifdef ELF_LIBRARY
  (user_h)(sig, foo, thread_context);
#else
  (user_h)(sig);
#endif

  foob = &sig;
  foob--;
  if(*foob == 0xffffffff){
    /* This must be a real SVr4 system.  Restore the thread context. */
    _setcontext(thread_context);
  }
}

int _sigaction(int sig, const struct sigaction * act,
	      struct sigaction * oact)
{
  int retval;
  sighandler_t old_h;
  struct sigaction save_sa;

  if(sig < 0 || sig > 31) {
    errno = EINVAL;
    return -1;
  };

  /* The SVr4 version is more complicated than ours because they support
     threads, and we do not */

  old_h = _siguhandler[sig];

#if 1
  if(act) {
    save_sa = *act;
    _siguhandler[sig] = (sighandler_t) act->sa_handler;
    if(act->sa_handler && act->sa_handler != SIG_IGN)
      save_sa.sa_handler = (sighandler_t *) _sigacthandler;
  };

  retval = __sigaction(sig, &save_sa, oact);
  

  if(retval == -1){
    _siguhandler[sig] =   old_h;
    return -1;
  };

  if(oact && oact->sa_handler != (sighandler_t *) _sigacthandler)
    oact->sa_handler = (sighandler_t *) old_h;

  return retval;
#else

  return __sigaction(sig, act, oact);;
#endif
}

#ifdef ELF_LIBRARY
__asm__(".weak sigaction; sigaction = _sigaction");
#endif
