/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#ifndef IDLER_H

#include "SDL.h"
#include "common.h"

/**
 * A timer class that tries to keep the FPS going the given rate
 * despite inaccurarities of the idle-function(SDL_Delay).
 */
class Idler {
public:
	Idler(uint fps):
		last_time(SDL_GetTicks()),
		real_last_time(last_time),
		ms_per_frame(1000/fps)
#ifdef COUNTFPS
		,frames(0), current_sec(0)
#endif
		{}

	/** Returns the number of milliseconds since the end
	 * of last idle operation */
	uint idle() {
#ifdef COUNTFPS
		{
			++frames;
			uint tmp = last_time/1000;
			if (current_sec < tmp) {
				fprintf(stderr, "Frames %i: %i\n", tmp, frames);
				frames = 0;
			}
			current_sec = tmp;
		}
#endif

		const uint now = SDL_GetTicks();
		last_time += ms_per_frame;

		if (last_time > now)
			SDL_Delay(last_time-now);

		// try to return sync if real fps has temporarily
		// dropped much under given fps
		if (last_time + 200 < now)
			last_time = now;

		int tmp_time = real_last_time;
		real_last_time = now;

		return real_last_time-tmp_time;
	}
	void reset() {
		last_time = real_last_time = SDL_GetTicks();
	}

private:
	uint last_time;
	uint real_last_time;
	uint ms_per_frame;	// FIXME: inaccurate; change to float?

#ifdef COUNTFPS
	uint frames;
	uint current_sec;
#endif
};

#define IDLER_H
#endif	// IDLER_H
