#ifndef TEXTURELOADER_H
#define TEXTURELOADER_H

#include "glut.h"

GLuint LoadTexture(const char * filename,int ScreenWidth,int ScreenHeight)
{
	GLuint texture;
	unsigned char * data;
	FILE * file;

	file = fopen(filename, "rb");
	if (file == NULL) return 0;

	data = (unsigned char *)malloc(ScreenWidth * ScreenHeight * 3);
	//int size = fseek(file,);
	fread(data, ScreenWidth * ScreenHeight * 3, 1, file);
	fclose(file);

	for (int i = 0; i < ScreenHeight * ScreenWidth; ++i)
	{
		int index = i * 3;
		unsigned char B, G,R;
		B = data[index];
		G = data[index + 1];
		R = data[index + 2];

		data[index] = R;
		data[index + 1] = G;
		data[index + 2] = B;
	}

	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 3, ScreenWidth, ScreenHeight, GL_RGB, GL_UNSIGNED_BYTE, data);

	free(data);
	return texture;
};

#endif