/***************************************************************************
 *            main.c
 *
 *  Thu Jan 27 02:46:34 2005
 *  Copyright  2005  Peter Baldwin
 *  pgbaldwi@uwaterloo.ca
 ****************************************************************************/

#include <stdlib.h>
#include <stdio.h>


#include <sys/time.h>
#include <unistd.h>

#include "ui.h"

typedef unsigned long clock_time;
#define CLOCKS_PER_SEC 1000000

clock_time mGetTime() {
	struct timeval time;
	gettimeofday( &time, NULL );
	return (clock_time)time.tv_sec * CLOCKS_PER_SEC + time.tv_usec;
}

/*
 * Start executing here.
 *   First initialize window.
 *   Next loop responding to events.
 *   Exit forcing window manager to clean up - cheesy, but easy.
 */
int main ( int argc, char *argv[] ) {
	clock_time current_time;
	clock_time last_time;
	clock_time sample_start;
	int frame_count;
	int fps;
	
	//limit frame-rate so as not to consume entire processor unless neccessary
	const int MIN_INTERVAL = CLOCKS_PER_SEC/60; 
	
	uiInit( argc, argv );
	
	frame_count = 0;
	last_time = mGetTime();
	sample_start = last_time;
	while( TRUE ) {
		current_time = mGetTime();
		clock_time dt = current_time - last_time;
		if (current_time - sample_start > CLOCKS_PER_SEC) {
			//reset sample
			fps = (int)((float)frame_count / ((float)(current_time - sample_start) / (float)CLOCKS_PER_SEC));
			sample_start = current_time;
			frame_count = 0;
			
		} else {
			frame_count++;
		}		
		uiTick((double)dt/ CLOCKS_PER_SEC);
		
		if (dt < MIN_INTERVAL) {
			usleep(MIN_INTERVAL - dt);
		}
		last_time = current_time;
	}
}
