#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <setjmp.h>
#include <signal.h>
#include <limits.h>
#include "myc_fortran.h"

void intcatch(int sig)
{ printf("\nuse quit (normally ctrl-\\) to interrupt\n");
}

int called=0; /* env is valid only if called==1 */
jmp_buf env;

void (*inthdl)(int sig)=intcatch;
void (*errhdl)(void);

void sighdl(int sig)
{ if (called) longjmp(env,sig);
}

void F_FUN(sys_err_hdl)(void errhdl0(void))
{ errhdl=errhdl0; }

void F_FUN(sys_int_hdl)(void inthdl0(int sig))
{ inthdl=inthdl0; }

void F_FUN(sys_try)(void proc(void))
{ int status;
  void (*sgh[32]) (int);

  assert(!called); /* nested calls not allowed */
  called=1;
  sgh[SIGFPE] =signal(SIGFPE, sighdl);
  sgh[SIGINT] =signal(SIGINT, *inthdl);
  status=setjmp(env);
  if (status==0) /* first return of setjmp */
  { proc(); }
  else
  { (*errhdl)(); };
  signal(SIGFPE, sgh[SIGFPE]);
  signal(SIGINT, intcatch);
  called=0;
}

void F_FUN(sys_abort)(void)
{ if (called) longjmp(env,-2);
}


void F_FUN(sys_exit_hdl)(void hdl(void))
{ atexit(hdl);
}
