#define _CRT_SECURE_NO_WARNINGS 1
#include "TGA.h"


bool TGA::readTextureDataTGA(const string& path, Texture<unsigned char>& dstData )
{
	//glPixelStorei(GL_UNPACK_ALIGNMENT, 1);          // zpusob ulozeni bytu v texure

	FILE               *fin;
    unsigned short int width=0, height=0;           // sirka a vyska obrazku
    unsigned short int palettelength;               // delta palety
    unsigned char      bpp=0;                       // pocet bitu na pixel
    unsigned char      tgaHeader[18];               // hlavicka formatu TGA
    if (!path.c_str()) return 0;
    fin=fopen(path.c_str(), "rb");
    if (!fin) return 0;                            // otevreni souboru se nezdarilo
    if (fread(tgaHeader, 18, 1, fin)!=1) return 0; // nacist hlavicku BMP souboru
    memcpy(&width, tgaHeader+12, 2);                // nacist sirku obrazku v pixelech
    memcpy(&height, tgaHeader+14, 2);               // nacist vysku obrazku v pixelech
    memcpy(&bpp, tgaHeader+16, 1);                  // nacist pocet bitu na pixel
    memcpy(&palettelength, tgaHeader+5, 2);         // nacist delku palety

	
	GLenum format;
	short chanelCount=0;
	
    switch (bpp) 
	{
        case 8: //BUG: is not working correct!!!
			chanelCount=1;
			format=GL_LUMINANCE;
            break;

        case 24:
			chanelCount=3;
			format=GL_RGB;
            break;

        case 32:
			chanelCount=4;
			format=GL_RGBA;
            break;

        default:
            assert(!" Unsuported TGA variant");
    }

	dstData.internalData.format = format;
	dstData.internalFormat = format;

	int size=width * height * chanelCount;

	dstData.internalData.pixelData.clear();
	dstData.internalData.pixelData.resize(size); 
	dstData.internalData.sizeX=width;
	dstData.internalData.sizeY=height;

	bool ok=true;
	//fread(tga->data, size_uchar, t, fh);

	if (fread( &dstData.internalData.pixelData[0], sizeof( unsigned char ) * size, 1, fin)!=1) ok=false;
	//if (fread( &dstData.internalData.pixelData[0], size, 1, fin)!=1) ok=false;

	if (chanelCount==3 || chanelCount==4)
	{
		for (int i=0;i<size;i=i+chanelCount)	//TGA je ulozen v BGR[A] a ja potrebuju RGB[A]
		{
			unsigned char pom;
			pom=dstData.internalData.pixelData[i];
			dstData.internalData.pixelData[i]=dstData.internalData.pixelData[i+2];
			dstData.internalData.pixelData[i+2]=pom;
		}
	}

	fclose(fin);

	return ok;
}