#include <stdio.h>
#include "texture.h"
#include "smalloc.h"

long texture_memused;

texture* texture_frompnm(char* filename, int size) {
	FILE* file;
	int discards; /* Number of lines discarded */
	unsigned char discard; /* Temporary discard buffer */
	int truestart; /* True start of data */
	texture* t = smalloc(sizeof(texture));
	t->size = size;
	t->name = filename;
	
	file = fopen(filename, "rb");
	if(!file) { fprintf(stderr, "Cannot load texture '%s'!\n", filename); exit(1); }
	
	/* Discard the pnm header (4 lines) */
	/* Only works for GIMP2-generated PNMs, which have an extra comment line */
	discards = 0; truestart = 0;
	while(discards < 4) {
		fread(&discard, 1, 1, file);
		if(discard == 0x0a)
			{ discards++; }
		truestart++;
	}
	
	fseek(file, 0, SEEK_END);
	t->memsize = ftell(file) - truestart;
	if(t->memsize != size * size * 3)
		{ fprintf(stderr, "Warning: PNM data size does not match expected texture size for '%s'.\n", filename); }
	fseek(file, truestart, SEEK_SET);
	t->pixels = smalloc(t->memsize);
	texture_memused += t->memsize;
	fread(t->pixels, 1, t->memsize, file);
	fclose(file);

	/* Now, let's bind that into a GLUT texture */
	glGenTextures(1, &t->id);
	glBindTexture(GL_TEXTURE_2D, t->id);
	glTexImage2D(GL_TEXTURE_2D, 0, 3, t->size, t->size, 0, GL_RGB, GL_UNSIGNED_BYTE, t->pixels);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	/* I suspect that I may be able to throw away the pixels now... */
	
	/*printf("Loaded texture '%s', %iKB, with ID %i\n", filename, t->memsize/1024, t->id);*/
	return t;
}

void texture_use(texture* t) {
	glBindTexture(GL_TEXTURE_2D, t->id);
}

long texture_memusage(void) {
	return texture_memused;
}
