/* cleanup - Peter and Karl's standard cleanup management
 *
 * "cleaned up" the documentation  3/1/88
 *
 */


/* Copyright (C) 1989 by Hackercorp, All Rights Reserved */

#include <exec/types.h>
#include <functions.h>
#include <exec/memory.h>
#include <stdio.h>

struct _clean 
{
	int (*function)();
	struct _clean *next;
} *cleanlist = NULL;

/* add_cleanup
 * given a function, add it to a list of functions to call when cleanup
 * is executed
 */
add_cleanup(function)
int (*function)();
{
	struct _clean *ptr;

	ptr = AllocMem(sizeof(struct _clean), MEMF_PUBLIC);
	if(!ptr)
		return 0;
	ptr->function = function;
	ptr->next = cleanlist;
	cleanlist = ptr;
}

/* cleanup
 * call all the functions that were passed as arguments to add_cleanup
 * this run
 */
cleanup()
{
	struct _clean *ptr;
	int (*f)();

	fflush(stdout);
	fflush(stderr);

	while(cleanlist) 
	{
		/* locate the next cleanup function and get the function pointer */
		ptr = cleanlist;
		cleanlist = cleanlist->next;
		f = ptr->function;

		/* cleanup must clean up after itself */
		FreeMem(ptr, sizeof(struct _clean));

		/* execute the function */
		(*f)();

		fflush(stdout);
		fflush(stderr);
	}
}

/* panic - abort with an error message */

short panic_in_progress = 0;

panic(s)
char *s;
{
	fflush(stdout);
	fprintf(stderr,"panic: %s\n",s);
	fflush(stderr);
	if (!panic_in_progress)
	{
		panic_in_progress = 1;
		cleanup();
		exit(10);
	}
	fprintf(stderr,"double panic!\n");
}

_abort()
{
	panic("^C or other C library abort");
}
