#include <stdlib.h>
#include <string.h>

#include "exception.h"

jmp_buf __exception_jmp_buf;                          
char * __exception_return;
int __exception_type_code;
char __exception_buffer[EXCEPTION_BUFFER_SIZE];

struct __exception_node {
   jmp_buf __jmp_buf;
   char * __return;
   int __type_code;
   struct __exception_node * next;
};

struct __exception_node * __p_head = 0;

void __exception_pop() 
{
   if(__p_head != 0) {
      struct __exception_node * temp = __p_head;

      __p_head = __p_head->next;

      memcpy(&__exception_jmp_buf, &(temp->__jmp_buf), sizeof(jmp_buf));

      __exception_return = temp->__return;

      __exception_type_code = temp->__type_code;

      free(temp);
   }
} 

void __exception_push()
{
   if(__p_head != 0) {
      struct __exception_node * temp;

      temp = malloc(sizeof(struct __exception_node));

      temp->next = __p_head;
 
      memcpy(&(temp->__jmp_buf), &__exception_jmp_buf, sizeof(jmp_buf));

      temp->__return = __exception_return;

      temp->__type_code = __exception_type_code;

      __p_head = temp;
   }
   else {
      __p_head = malloc(sizeof(struct __exception_node));

      __p_head->next = 0;

      memcpy(&(__p_head->__jmp_buf), &__exception_jmp_buf, sizeof(jmp_buf));

      __p_head->__return = __exception_return;

      __p_head->__type_code = __exception_type_code;
   } 
}

