#include "scheme.h"

static WEAK_NODE *first;

void Call_Terminators();

Init_Terminate () {
    Register_After_GC (Call_Terminators);
}

Register_Terminate (obj, func) Object obj; void (*func)(); {
    WEAK_NODE *p;

    p = (WEAK_NODE *)Safe_Malloc (sizeof (*p));
    p->object = obj;
    p->terminate = func;
    p->next = first;
    first = p;
}

Deregister_Terminate (obj) Object obj; {
    WEAK_NODE *p, **pp;

    for (pp = &first; (p = *pp); ) {
	if (EQ(p->object, obj)) {
	    *pp = p->next;
	    free ((char *)p);
	} else pp = &p->next;
    }
}

Terminate_All (type) int type; {
    WEAK_NODE *p, **pp;

    for (pp = &first; (p = *pp); ) {
	if (TYPE(p->object) == type) {
	    p->terminate(p->object);
	    *pp = p->next;
	    free ((char *)p);
	} else pp = &p->next;
    }
}

void Call_Terminators () {
    WEAK_NODE *p, **pp;

    for (pp = &first; (p = *pp); ) {
	if (IS_ALIVE(p->object)) {
	    if (WAS_FORWARDED(p->object))
		UPDATE_OBJ(p->object);
	    pp = &p->next;
	} else {
	    p->terminate(p->object);
	    *pp = p->next;
	    free ((char *)p);
	}
    }
}
