/*  
** Copyright (c) 1995 Netsurfer Inc.  All Rights Reserved.
**
** Author: <bbum@friday.com>
*/

/*  This object is included in the MiscKit by permission from the author
**  and its use is governed by the MiscKit license, found in the file
**  "LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
**  for a list of all applicable permissions and restrictions.
*/

#import <appkit/appkit.h>

#import "../surfimage.h"
#import "SurfTIFFDecoder.h"
	
@implementation SurfTIFFDecoder
/*"
 * Since TIFF is the native image type under NEXTSTEP, there is very little
 * for this image decoder to do.
"*/

+ sharedInstance
/*"
 * A convenience method for managing a single, shared instance of the
 * decoder.
"*/
{
	static id sharedInstance = nil;

	if (!sharedInstance) {
		sharedInstance = [self alloc];
		[sharedInstance init]; 
	}
	return sharedInstance;
}

+ (const char *const *)imageUnfilteredFileTypes;
/*"
 * Returns a NULL terminated array of file extensions that an instance of
 * this decoder can decode.
"*/
{
	static const char *const tiffTypes[] = {
		"tif",
		"TIF",
		"tiff",
		"TIFF",
		NULL};
	return tiffTypes;
}

+ (BOOL)canLoadFromStream:(NXStream *)stream
/*"
 * Returns YES if an instance of this decoder can likely decode the
 * contents of stream.
"*/
{
	long startingPosition = NXTell(stream);
	BOOL canRead		  = NO;
	unsigned index;
	unsigned char header[4];
	unsigned short iiBuf[] = {0x49, // I
							  0x49, // I
							  0x2A, // arbitrary 42 (long)
							  0x00};// arbitrary 42 (long)
	unsigned short mmBuf[] = {0x4D, // M
							  0x4D, // M
							  0x00, // arbitrary 42 (long)
							  0x2A};// arbitrary 42 (long)


	if(!NXRead(stream, header, 4))
		goto resetAndReturn;

	for(index = 0;index<4;index++)
		if(iiBuf[index] != header[index])
			break;
	canRead = (index == 4);

	if(!canRead) { 
		for(index = 0;index<4;index++)
			if(mmBuf[index] != header[index])
				break;
		canRead = (index == 4);
	}
	
resetAndReturn:
    /* Reset stream back to the starting postiion.
     */
	NX_DURING
	NXSeek(stream, startingPosition, NX_FROMSTART);
	NX_HANDLER
	NXLogError("Attempted to NXSeek() a stream that cannot be NXSeek()ed.");
	canRead = NO;
	NX_ENDHANDLER

	return canRead;
}

- _decodeFromStream: (NXStream *) theStream
{
	id bitmapIR = [[NXBitmapImageRep allocFromZone:[self zone]]
					   initFromStream: theStream];
	if(bitmapIR) {
		[returnImage useRepresentation: bitmapIR];
		return returnImage;
	} else {
		return nil;
	}
}
@end
