[email protected]
#include <stdio.h>
#include "SDL_image.h"
#ifdef LOAD_TIF
#include <tiffio.h>
static tsize_t tiff_read(thandle_t fd, tdata_t buf, tsize_t size)
{
	return SDL_RWread((SDL_RWops*)fd, buf, 1, size);
}
static toff_t tiff_seek(thandle_t fd, toff_t offset, int origin)
{
	return SDL_RWseek((SDL_RWops*)fd, offset, origin);
}
static tsize_t tiff_write(thandle_t fd, tdata_t buf, tsize_t size)
{
	return SDL_RWwrite((SDL_RWops*)fd, buf, 1, size);
}
static int tiff_close(thandle_t fd)
{
	
	return 0;
}
static toff_t tiff_size(thandle_t fd)
{
	Uint32 save_pos;
	toff_t size;
	save_pos = SDL_RWtell((SDL_RWops*)fd);
	SDL_RWseek((SDL_RWops*)fd, 0, SEEK_END);
        size = SDL_RWtell((SDL_RWops*)fd);
	SDL_RWseek((SDL_RWops*)fd, save_pos, SEEK_SET);
	return size;
}
int IMG_isTIF(SDL_RWops* src)
{
	TIFF* tiff;
	TIFFErrorHandler prev_handler;
	
	prev_handler = TIFFSetErrorHandler(NULL);
	
	
	
	tiff = TIFFClientOpen("SDL_image", "rm", (thandle_t)src, 
		tiff_read, tiff_write, tiff_seek, tiff_close, tiff_size, NULL, NULL);
	
	TIFFSetErrorHandler(prev_handler);
	
	if(!tiff)
		return 0;
	
	TIFFClose(tiff);
	
	return 1;
}
SDL_Surface* IMG_LoadTIF_RW(SDL_RWops* src)
{
	TIFF* tiff;
	SDL_Surface* surface = NULL;
	Uint32 img_width, img_height;
	Uint32 Rmask, Gmask, Bmask, Amask, mask;
	Uint32 x, y;
	Uint32 half;
	if ( !src ) {
		
		return NULL;
	}
	
	tiff = TIFFClientOpen("SDL_image", "rm", (thandle_t)src, 
		tiff_read, tiff_write, tiff_seek, tiff_close, tiff_size, NULL, NULL);
	if(!tiff)
		return NULL;
	
	TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &img_width);
	TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &img_height);
	Rmask = 0x000000FF;
	Gmask = 0x0000FF00;
	Bmask = 0x00FF0000;
	Amask = 0xFF000000;
	surface = SDL_AllocSurface(SDL_SWSURFACE, img_width, img_height, 32,
		Rmask, Gmask, Bmask, Amask);
	if(!surface)
		return NULL;
	
	if(!TIFFReadRGBAImage(tiff, img_width, img_height, surface->pixels, 0))
		return NULL;
	
	half = img_height / 2;
	for(y = 0; y < half; y++)
	{
	        Uint32 *top = (Uint32 *)surface->pixels + y * surface->pitch/4;
	        Uint32 *bot = (Uint32 *)surface->pixels
		              + (img_height - y - 1) * surface->pitch/4;
		for(x = 0; x < img_width; x++)
		{
		        Uint32 tmp = top[x];
			top[x] = bot[x];
			bot[x] = tmp;
		}
	}
	TIFFClose(tiff);
	
	return surface;
}
#else
int IMG_isTIF(SDL_RWops *src)
{
	return(0);
}
SDL_Surface *IMG_LoadTIF_RW(SDL_RWops *src)
{
	return(NULL);
}
#endif