/*--------------------------------------------------------------------------
 * File: tga.c
 * Written by: Alexander Boczar, 1997-04-16
 * Description: Targa image loader
 *
 * Updates:
 * -- Date -- | ----- Name ----- |-- Did what....
 * 1997-xx-xx | Alexander Boczar |
 *
 * Todo:
 *
 -------------------------------------------------------------------------------*/

#include "system/xstdio.h"
#include "formats/vio.h"
#include "formats/tga.h"

VIO *tga_load( char *filename)
{
	VIO *image;
	BGR *src;
	RGB *dst;
	XFILE *f;
	int x,y;

	if ( (f = xfopen( filename, "rb")) == NULL)
		return( NULL);

	if ( xfrle_dword( f) != 0x00000200)
	{
		xfclose( f);
		return( NULL);
	}

	xfseek( f, 12, SEEK_SET);

	image = (VIO *)xmalloc( sizeof(VIO));

	image->width = xfrbe_word( f);
	image->height = xfrbe_word( f);
	image->flags = VIOFLAG_24BIT;

	xfseek( f, 2, SEEK_CUR); //Skip the other two bytes

	image->image24 = (RGB *)xmalloc( image->width * image->height * sizeof(RGB));

	src = (BGR *)xmalloc( image->width * sizeof( BGR));
	dst = image->image24 + (image->width * (image->height - 1));
	for( y=0; y<image->height; y++)
	{
		xfread( src, sizeof( BGR), image->width, f);
		for( x=0; x<image->width; x++)
		{
			dst->r = src[x].r;
			dst->g = src[x].g;
			dst->b = src[x].b;
			dst++;
		}
		dst -= (image->width << 1);
	}
	xfree( src);

	xfclose( f);
	return( image);
}

