// COR.CPP
#include "cor.hpp"
#include ...

extern void ctxtswc(void);
coroutine *MAINC=new coroutine();
coroutine *PREVIOUS,*CURRENT=MAINC;

coroutine::coroutine() {
	word *sp,*stkBase;
	stkSize= 2 * sizeof(word);
	stkBase=(word *) farmalloc(stkSize);
	stkSegment=FP_SEG(stkBase);
	stkOffset=FP_OFF(stkBase);
	sp=stkBase + 2;
	*--sp=(word) startProcess;}

coroutine::~coroutine() {
	delete(MK_FP(stkSegment,stkOffset));}

void coroutine::superMain(void) {
	main();
	resume(MAINC);
	FATAL("terminated coroutine resumed");}

void startProcess(void) {
	CURRENT->superMain();}

void resume(coroutine* rc)
{	word sp,*stkBase;
	if ((CURRENT != NULL) && (rc != CURRENT) &&
	    (rc != NULL)) {
		sp=_SP;
		CURRENT->stkSize= _stklen - sp + 4;
		stkBase=
		   (word*)farmalloc(CURRENT->stkSize);
		CURRENT->stkSegment=FP_SEG(stkBase);
		CURRENT->stkOffset=FP_OFF(stkBase);
		PREVIOUS=CURRENT;
		CURRENT=rc;
		ctxtswc();
		delete(MK_FP(CURRENT->stkSegment,
		             CURRENT->stkOffset));
	}
}

void detach(void) {
	resume(MAINC);}

