#include <GL/gl.h>
#include <mgl/gl.h>
#include <proto/exec.h>

void __mgl_init_semaphore(void) __attribute__((constructor));
void __mgl_term_semaphore(void) __attribute__((destructor));

struct GLContextIFace *mini_CurrentContext;

static struct MGLSemaphore __mgl_semaphore = {
	{   /* SignalSemaphore */
		{0,0,0,0,0}, /* Node */
		0,           /* WORD */
		{0,0,0},     /* MinList */
		{{0,0},0},   /* SemaphoreRequest */
		0,           /* Task* */
		0            /* WORD */
	},
	0  /* Context */
};

static char __mgl_semaphore_name[20];

/* This rather strange code is a "simulated" named shared memory, used by SDL
 * to find the main progarm's context pointer. 
 */
 
void __mgl_init_semaphore(void)
{
	char *digits = "0123456789abcdef";
	int i;
	uint32 task = (uint32)IExec->FindTask(0);
	IExec->InitSemaphore(&__mgl_semaphore.semaphore);
	
	/* Construct a name */
	__mgl_semaphore_name[0] = 'm';
	__mgl_semaphore_name[1] = 'g';
	__mgl_semaphore_name[2] = 'l';
	__mgl_semaphore_name[3] = '_';
	__mgl_semaphore_name[4] = '0';
	__mgl_semaphore_name[5] = 'x';
	
	for (i = 0; i < 8; i++)
	{
		__mgl_semaphore_name[(7-i)+6] = digits[task&0xf];
		task >>= 4;
	}
	
	__mgl_semaphore_name[14] = 0;
	
	__mgl_semaphore.semaphore.ss_Link.ln_Name = __mgl_semaphore_name;
	__mgl_semaphore.semaphore.ss_Link.ln_Pri = 0;
	__mgl_semaphore.context = &mini_CurrentContext;
	
	IExec->AddSemaphore(&__mgl_semaphore.semaphore);
}

void __mgl_term_semaphore(void)
{
	if (__mgl_semaphore.semaphore.ss_Link.ln_Name != 0)
	{
		IExec->RemSemaphore(&__mgl_semaphore.semaphore);
	}	 
}

