
#ifndef __Image_Header_File_
#define __Image_Header_File_


#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <exception>
#include <memory.h>


namespace vam
{
	/// TGA Image Loader from http://gpwiki.org/index.php/LoadTGACpp
    // TGA Loader - 16/11/04 Codehead


#define IMG_OK              0x1
#define IMG_ERR_NO_FILE     0x2
#define IMG_ERR_MEM_FAIL    0x4
#define IMG_ERR_BAD_FORMAT  0x8
#define IMG_ERR_UNSUPPORTED 0x40

	
	struct TGAException : public std::exception
	{
		std::string fn;
		int err;
		TGAException(std::string fileName, int errCode): fn(fileName), err(errCode){}
		virtual const char* what() const throw()
		{
			std::ostringstream oss;
			oss << "Loading: " << fn;
			switch (err)
			{
			case IMG_ERR_NO_FILE:
				oss << " - not found";
				break;

			case IMG_ERR_MEM_FAIL:
				oss << " - memory allocation failed";
				break;

			case IMG_ERR_BAD_FORMAT:
				oss << " - bad image format";
				break;

			case IMG_ERR_UNSUPPORTED:
				oss << " - unsupported image format";
				break;
			}

			return oss.str().c_str();
		}
		virtual ~TGAException() throw() {}
	};

	class TGAImg
	{
	public:
		TGAImg();
		~TGAImg();
		void loadFile(std::string fileName)
		{
			int ret = load(fileName.c_str());
			if (ret != IMG_OK)
			{
				throw TGAException(fileName, ret);
			}
		}

		int load(const char* szFilename);
		int getBPP();
		int getWidth();
		int getHeight();
		unsigned char* getImg();	   // Return a pointer to image data
		unsigned char* getPalette();   // Return a pointer to VGA palette

	private:
		short int iWidth,iHeight,iBPP;
		unsigned long lImageSize;
		char bEnc;
		unsigned char *pImage, *pPalette, *pData;

		// Internal workers
		int readHeader();
		int loadRawData();
		int loadTgaRLEData();
		int loadTgaPalette();
		void BGRtoRGB();
		void flipImg();
	};


} // end of namespace


#endif //__Image_Header_File_


