#ifndef IN_UNIXINT
#include "include.h"

#include <signal.h>
#endif

#include "usig.h"

char signals_handled[];

void
gcl_signal(signo,handler)
     int signo;
     void (*handler)();
{
  char *p = signals_handled;
  while (*p)
    { if (*p==signo)
	{our_signal_handler[signo] = handler;
	 handler = main_signal_handler;
	 break;
       }
      p++;}
 
  {      
  
#ifdef HAVE_SIGACTION
    struct sigaction action;
    action.sa_handler = handler;
    action.sa_flags = SA_RESTART | (signo == SIGSEGV || signo == SIGBUS ? SV_ONSTACK : 0)
#ifdef SA_SIGINFO
    | SA_SIGINFO
#endif      
      ;
    sigemptyset(&action.sa_mask);
    sigaddset(&action.sa_mask,signo);
    sigaction(signo,&action,0);
#else
#ifdef HAVE_SIGVEC
    struct sigvec vec;
    vec.sv_handler =  handler;
    vec.sv_flags =  (signo == SIGSEGV || signo == SIGBUS ? SV_ONSTACK : 0);
    vec.sv_mask = sigmask(signo);
    sigvec(signo,&vec,0);
#else
    signal(signo,handler);
#endif
#endif
  }
}

/* remove the signal n from the signal mask */

unblock_signal(n)
{ int current_mask;
  current_mask = sigblock(0);
  return sigsetmask(~(sigmask(n)) & current_mask);
}

unblock_sigusr_sigio()
{ int current_mask;
  current_mask = sigblock(0);
  return sigsetmask(~(sigmask(SIGIO))&~(sigmask(SIGUSR1)) & current_mask);
}


void
sigfpe()
{
	gcl_signal(SIGFPE, sigfpe);
	FEerror("Floating-point exception.", 0);
}
sigpipe()
{
	gcl_signal(SIGPIPE, sigpipe);
	perror("");
	FEerror("Broken pipe", 0);
}


void
sigint()
{
  unblock_signal(SIGINT);
  terminal_interrupt(1);
}



void
sigalrm()
{
  raise_pending_signals(sig_try_to_delay);
}

DEFVAR("*INTERRUPT-ENABLE*",sSAinterrupt_enableA,SI,sLt,"");

DEF_ORDINARY("SIGUSR1-INTERRUPT",sSsigusr1_interrupt,SI,"");
DEF_ORDINARY("SIGIO-INTERRUPT",sSsigio_interrupt,SI,"");

void
sigusr1()
{ifuncall1(sSsigusr1_interrupt,Cnil);}

void
sigio()
{ifuncall1(sSsigio_interrupt,Cnil);}



void
install_default_signals()
{	gcl_signal(SIGFPE, sigfpe);
	gcl_signal(SIGPIPE, sigpipe);
	gcl_signal(SIGINT, sigint);
	gcl_signal(SIGUSR1, sigusr1);
	gcl_signal(SIGIO, sigio);
	gcl_signal(SIGALRM, sigalrm);
	
	install_segmentation_catcher();
	signals_allowed = sig_normal;
      }


	

