/*
*	ImageBMP.cpp
*
*	Programmé par Hillaire Sébastien
*
*
*	Se référé au fichier en-tête .h pour plus de détail
*
*/

#include "ImageBMP.h"
#include "MemoryManager/DebugNew.h"

using namespace RenderSystem;

ImageBMP::ImageBMP()
{
	datas=NULL;
}

ImageBMP::~ImageBMP()
{
	delete [] datas;
}

bool ImageBMP::load(char *filepath)
{
	bool ret=false;
	FILE *f=NULL;

	f=fopen(filepath,"rb");

	if(f!=NULL)
	{
		//lecture de l'en-tête
		fread(&bmph.bfType,1,sizeof(unsigned short),f);
		fread(&bmph.bfSize,1,sizeof(unsigned int),f);
		fread(&bmph.bfReserved1,1,sizeof(unsigned short),f);
		fread(&bmph.bfReserved2,1,sizeof(unsigned short),f);
		fread(&bmph.bfOffBits,1,sizeof(unsigned int),f);
		//en commentaire ==> ce qui ne marche pas
/*		if (bmph.bfOffBits==794)
		{
			fread(&bmph.biSize,1,4,f);
			fread(&bmph.biWidth,1,2,f);
			fread(&bmph.biHeigth,1,2,f);
			fread(&bmph.biPlanes,1,2,f);
			fread(&bmph.biBitCount,1,2,f);
		};*/
//		if (bmph.bfOffBits==1078)
//		{
			fread(&bmph.biSize,1,sizeof(unsigned int),f);
			fread(&bmph.biWidth,1,sizeof(unsigned int),f);
			fread(&bmph.biHeigth,1,sizeof(unsigned int),f);
			fread(&bmph.biPlanes,1,sizeof(unsigned short),f);
			fread(&bmph.biBitCount,1,sizeof(unsigned short),f);
			fread(&bmph.biCompression,1,sizeof(unsigned int),f);
			fread(&bmph.biSizeImage,1,sizeof(unsigned int),f);
			fread(&bmph.biXPelsPerMeter,1,sizeof(unsigned int),f);
			fread(&bmph.biYPelsPerMeter,1,sizeof(unsigned int),f);
			fread(&bmph.biClrUsed,1,sizeof(unsigned int),f);
			fread(&bmph.biClrImportant,1,sizeof(unsigned int),f);
//		};

		if(bmph.biBitCount==24)
		{
			ret=true;	//pour mettre à true, le fichier doit existé et l'image doit être en 24bits

			datas = new unsigned char[(unsigned int)bmph.biWidth*(unsigned int)bmph.biHeigth*3];

			//chargement des données au format du fichier : BGR
			fread(&datas[0], sizeof(unsigned char), (unsigned int)bmph.biWidth*(unsigned int)bmph.biHeigth*3, f);

			//mise à jour des donnée au format RGB
			unsigned char tmp;
			for(unsigned int i=0;i<(unsigned int)bmph.biWidth*(unsigned int)bmph.biHeigth*3;i+=3)
			{
				tmp=datas[i];
				datas[i]=datas[i+2];
				datas[i+2]=tmp;
			}
		}

		fclose(f);
	}
	
	return ret;
}

unsigned int ImageBMP::getWidth()
{
	return (unsigned int)bmph.biWidth;
}

unsigned int ImageBMP::getHeight()
{
	return (unsigned int)bmph.biHeigth;
}

unsigned short ImageBMP::getBPP()
{
	return (unsigned int)bmph.biBitCount;
}

unsigned char* ImageBMP::getDatasPointer()
{
	return &datas[0];
}
