/*
    IMGLIB:  An example image loading library for use with SDL
    Copyright (C) 1999  Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Sam Lantinga
    5635-34 Springhouse Dr.
    Pleasanton, CA 94588 (USA)
    slouken@devolution.com
*/

/* A simple library to load images of various formats as SDL surfaces */

#include <stdio.h>

#include "IMG.h"

/* Table of image detection and loading functions */
static struct {
	char *type;
	int (*is)(SDL_RWops *src);
	SDL_Surface *(*load)(SDL_RWops *src);
} supported[] = {
	{ "BMP", IMG_isBMP, IMG_LoadBMP_RW },
	{ "PPM", IMG_isPPM, IMG_LoadPPM_RW },
	{ "PCX", IMG_isPCX, IMG_LoadPCX_RW },
	{ "GIF", IMG_isGIF, IMG_LoadGIF_RW },
	{ "JPG", IMG_isJPG, IMG_LoadJPG_RW },
	{ "TIF", IMG_isTIF, IMG_LoadTIF_RW },
	{ "PNG", IMG_isPNG, IMG_LoadPNG_RW },
	{ NULL, NULL, NULL }
};

/* Load an image from an SDL datasource */
SDL_Surface *IMG_Load_RW(SDL_RWops *src, int freesrc)
{
	int i, start;
	SDL_Surface *image;

	/* Make sure there is something to do.. */
	if ( src == NULL ) {
		return(NULL);
	}

	/* See whether or not this data source can handle seeking */
	if ( SDL_RWseek(src, 0, SEEK_CUR) < 0 ) {
		SDL_SetError("Can't seek in this data source");
		return(NULL);
	}

	/* Detect the type of image being loaded */
	start = SDL_RWtell(src);
	image = NULL;
	for ( i=0; supported[i].type && !image; ++i ) {
		SDL_RWseek(src, start, SEEK_SET);
		if ( supported[i].is(src) ) {
#ifdef DEBUG_IMGLIB
			fprintf(stderr, "IMGLIB: Loading image as %s\n",
							supported[i].type);
#endif
			SDL_RWseek(src, start, SEEK_SET);
			image = supported[i].load(src);
		}
	}

	/* Clean up, check for errors, and return */
	if ( freesrc ) {
		SDL_RWclose(src);
	}
	if ( image == NULL ) {
		SDL_SetError("Unsupported image format");
	}
	return(image);
}

