#include "main.h"
#include "timeloop.h"


static volatile int true_time;

static void timeloop_handler(void)
{
	true_time++;
}
END_OF_STATIC_FUNCTION(timeloop_handler)


void init_timeloop(void)
{
	LOCK_FUNCTION(timeloop_handler);
	LOCK_VARIABLE(true_time);
}


int logic_time;


int timeloop(void (*draw)(void *data), int (*update)(void *data), void *data, int speed)
{
	logic_time = 0;
	true_time = 0;
	install_int_ex(&timeloop_handler, speed);
	for (;;) {
		al_poll_duh(adp);
		(*draw)(data);
		while (logic_time - true_time >= 0) {
			al_poll_duh(adp);
			yield_timeslice();
		}
		while (logic_time - true_time < 0) {
			int rv;
			al_poll_duh(adp);
			rv = (*update)(data);
			logic_time++;
			if (rv) {
				remove_int(&timeloop_handler);
				return rv;
			}
		}
	}
}


void timeloop_speed(int speed)
{
	install_int_ex(&timeloop_handler, speed);
}
