#include <windows.h>
#include <mmsystem.h>
#include "stdinclu.h"

static LARGE_INTEGER Frequency, TimeZero, Time;

void calculateFps(float time);

void COUNTER_Initialize(void)
{
	QueryPerformanceFrequency((LARGE_INTEGER *)&Frequency);
}

void COUNTER_SetZero(void)
{
	QueryPerformanceCounter((LARGE_INTEGER *)&TimeZero);
}

long general = 0;
int zeros = 0;

float COUNTER_Get(void)
{
	QueryPerformanceCounter((LARGE_INTEGER *)&Time);
	long nframe = MAX_FPS*((Time.LowPart - TimeZero.LowPart))/(float)Frequency.LowPart;
	if (nframe >= 3570)
	{
		COUNTER_SetZero();
		nframe -= 3570;
		zeros ++;
	}
	
	general = nframe + (3569*zeros);

	float time = (float)general/MAX_FPS;

	if (genFps) calculateFps(time);

	return (time);
}

void printTime(float time)
{
	int min = time/60;
	int tex = 0, blend = 0;
	float seg = time-(min*60);

	//Draws actual time
	glPushMatrix();
	glLoadIdentity();

	if(glIsEnabled(GL_TEXTURE_2D)){
		glDisable(GL_TEXTURE_2D);
		tex=1;
	}
	if(glIsEnabled(GL_BLEND)){
		glDisable(GL_BLEND);
		blend=1;
	}

	glColor3f(0.1f, 0.8f, 0.1f);
	glTranslatef(0.0f, 0.037f, -0.1f);
	glScalef(0.005f, 0.005f, 1.0f);
	if (seg<10)
		glPrint("Time  0%i:0%.2f", min, seg);
	else glPrint("Time  0%i:%.2f", min, seg);
	
	if(tex)	glEnable(GL_TEXTURE_2D);
	if(blend) glEnable(GL_BLEND);

	glPopMatrix();
}


float fps = 0.0f;
int instantCont = 0;
int instantMax = 70;

struct instant
{
	float skip;
	instant *next;
	instant *prev;
};

instant *first = NULL;
instant *last = first;
instant *temp = NULL;

static float lastTime = 0.0f;

void calculateFps (float time)
{
	if (first != NULL)	//introduce next element in tail
	{
		temp = first;
		first = new instant;
		first->next = temp;
		temp->prev = first;
		first->prev = NULL;
		if (instantCont == instantMax)	//if the tail is comlete eliminate the last element
		{
			last = last->prev;
			delete(last->next);
			last->next = NULL;
		}
		else instantCont++;
	}
	else	//introduce the first element in tail
	{
		first = new instant;
		first->next = NULL;
		first->prev = NULL;
		last = first;
		instantCont++;
	}

	first->skip = time - lastTime;		
		
	//Calculates skip frames stored in the tail average
	temp = first;
	fps = 0.0f;
	while (temp != NULL)
	{
		fps+= temp->skip;
		temp = temp->next;
	}
	if (fps != 0.0f) //not divide by zero
		fps = (float)(1/(fps/instantMax));

	lastTime = time;
}

void printFps(float time)
{
	int tex = 0, blend = 0;

	//Draws frames per second average
	glPushMatrix();
	glLoadIdentity();

	if(glIsEnabled(GL_TEXTURE_2D)){
		glDisable(GL_TEXTURE_2D);
		tex=1;
	}
	if(glIsEnabled(GL_BLEND)){
		glDisable(GL_BLEND);
		blend=1;
	}
	
	glColor3f(0.1f, 0.8f, 0.1f);
	glTranslatef(0.047f, -0.04f, -0.1f);
	glScalef(0.005f, 0.005f, 1.0f);
	glPrint("fps: %.1f", fps);

	if(tex)	glEnable(GL_TEXTURE_2D);
	if(blend) glEnable(GL_BLEND);

	glPopMatrix();
}