/*
 * Copyright (C) 2003 Clemens Fuchslocher
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

#include <iostream>

#ifdef __MINGW32__
#include <windows.h>
#else
#include <time.h>
#include <sys/time.h>
#endif

#include "FramesPerSecond.h"


namespace nsToolkit {

FramesPerSecond::FramesPerSecond(void)
{
	this->reset();
}


unsigned long FramesPerSecond::getTimeAsMilliseconds(void)
{
#ifdef __MINGW32__
	return GetTickCount();
#else
	struct timeval n;
	if (gettimeofday(&n, NULL) == -1)
	{
		std::cerr << __FILE__ << '[' << __LINE__ << "]: gettimeofday()" << std::endl;
	}

	return n.tv_sec * 1000 + n.tv_usec / 1000;
#endif
}


void FramesPerSecond::reset(void)
{
	this->frames = 0;
	this->framesPerSecond = 0;
	this->last = 0;
}


void FramesPerSecond::operator++ (int)
{
	this->frames++;

	if (this->last == 0)
	{
		this->last = this->getTimeAsMilliseconds();
	}
}


float FramesPerSecond::getFramesPerSecond(void)
{
	unsigned long now = this->getTimeAsMilliseconds();

	if (this->last == 0)
	{
		this->last = now;
		return 0;
	}

	unsigned long ms = now - this->last;
	if (ms > 1000)
	{
		this->framesPerSecond = this->frames / (ms / 1000.0);
		this->last = now;
		this->frames = 0;
	}

	return this->framesPerSecond;
}

}
