#include "assert.h"
#include <signal.h>

GLOBAL assert_c assert_foo("GLOBAL", 0, "");
BOOL assert_c::desperate = FALSE;
C char * assert_c::MARK = "MARK:";
C char * assert_c::EXIT = "EXIT:";
assert_c *assert_c::top = 0;
assert_c *assert_c::bot = 0;

LOCAL void
sighandler(int n)
{
 cerr << "SIGNAL " << n << " CAUGHT." << endl;
 assert_c::trace();
 abort();
}


assert_c::assert_c(C char *f, int line, C char *funct)
	: filename(f), functname(funct)
{
 if(!top)	{
	top=this;
	signal(SIGINT, sighandler);
	signal(SIGFPE, sighandler);
	}
 if(!bot)	bot=this;
 linenum = line;
 top->next = this;
 back = top;
 next = this;
 top = this;
 dcheck("ENTER:");
}

int assert_c::trace()
{
 IMPORT assert_c assert_foo;
 BOOL go = FALSE;
 Cassert_c *p = bot;
 if(!p || !p->next)
	cerr << "ASSERT TRACE: beginning of stack corrupted" << endl;
 do	{
	if(p->next!=p && p->next->back!=p)
		cerr << "ASSERT TRACE: stack corrupted" << endl;
	cerr << p->filename << ':' << p->functname << ':' << p->linenum << endl;
	go = p->next!=p;
	p = p->next;
	}	while(go);
 return 0;
}

void assert_c::dcheck(C char * s) C
{
 if(desperate)	{
		cerr << s << filename << ':' << functname << ':' << linenum << endl;
	}
}
