/* 
   Copyright 1994-2003 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 
   USA

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#include "libp.h"

#define MAX_ATEXIT 32

extern int _RTL_DATA _abterm;

static int atexitval = 0;
static void (*funclist[MAX_ATEXIT])(void);

static struct _onx_l {
	struct _onx_l *next;
	onexit_t func;
} *onx_list;

#pragma rundown __procexit 49

void __procexit(void)
{
	int i;
   __ll_enter_critical() ;
	if (!_abterm)
	{
		for (i=atexitval; i >0; i--)
			(*funclist[i-1])();
		while (onx_list)
		{
			(*onx_list->func)();
			onx_list = onx_list->next;
		}
	}
   __ll_exit_critical() ;
}

int _RTL_FUNC atexit(atexit_t func)
{
   __ll_enter_critical() ;
	if (atexitval < MAX_ATEXIT) {
		funclist[atexitval++] = func;
      __ll_exit_critical() ;
	  return 0;
	}
  __ll_exit_critical() ;
  return -1;
}
onexit_t _RTL_FUNC onexit(onexit_t func)
{
	struct _onx_l *l = malloc(sizeof(struct _onx_l));
	if (!l)
		return NULL;
   __ll_enter_critical() ;
   l->next = onx_list;
   onx_list = l;
   l->func = func;
  __ll_exit_critical() ;
  return func;
}
_onexit_t _RTL_FUNC _onexit(_onexit_t func)
{
	return onexit(func);
}
