// Texture.cpp

#include <windows.h>

#include "Types.h"
#include "File.h"
#include "Misc.h"
#include "Texture.h"


CTexture::CTexture()
{
	Data = NULL;
}


CTexture::~CTexture()
{
	delete [] Data;
	Data = NULL;
}


s32 CTexture::LoadBMP( const char *filename )
{
	CFile
		file;
	BITMAPFILEHEADER
		bfh;
	BITMAPINFOHEADER
		bih;
	s32
		y,
		w,
		depth,
		offset;

	delete [] Data;
	Data = NULL;


	if (!file.Open( filename ))
	{
		Error( "Cannot open: '%s'", filename );
		return( FALSE );
	}

	file.Read( &bfh, sizeof( BITMAPFILEHEADER ) );

	if (bfh.bfType != 0x4d42)
	{
		file.Close();
		Error( "'%s' is not a BMP file.", filename );
		return( FALSE );
	}

	file.Read( &bih, sizeof( BITMAPINFOHEADER ) );

	Width = bih.biWidth;
	Height = bih.biHeight;

	depth = (bih.biPlanes * bih.biBitCount);

	if (depth != 8)
	{
		file.Close();
		Error( "'%s' is not 8-bit.", filename );
		return( FALSE );
	}

	file.Read( Palette, 256*4 );

	Data = new u8[Width * Height];
	w = (Width + 3) & ~3;

	for (y=0; y<Height; y++)
	{
		offset = (Height - y - 1) * w;
		file.Seek( bfh.bfOffBits+offset );
		file.Read( &Data[y * Width], Width );
	}

	file.Close();

	return( TRUE );
}
