/*	MiscTIFFDecoder.m

	Copyright 1996 Netsurfer Inc.

	This notice may not be removed from this source code.
	The use and distribution of this software is governed by the
	terms of the MiscKit license agreement.  Refer to the license
	document included with the MiscKit distribution for the terms.

	Author: <bbum@friday.com>
	Converted to OpenStep, September 1996, Uwe Hoffmann.
*/


#import <AppKit/AppKit.h>

#import "MiscTIFFDecoder.h"

#ifdef VERBOSE
#undef VERBOSE
#undef METHOD
#undef METHODnl
#endif

#define VERBOSE 		if(_SDFlags.verboseMode)
#define METHOD  		NSLog(@"[%@ %s%@] ", \
                                [[self class] description], \
                 		        (self == (id)[self class]) ? "+" : "-", \
				                NSStringFromSelector(_cmd))
#define METHODnl  		NSLog(@"[%@ %s%@]\n", \
                                [[self class] description], \
                 		        (self == (id)[self class]) ? "+" : "-", \
				                NSStringFromSelector(_cmd))



@implementation MiscTIFFDecoder

+ sharedInstance
{
	static id sharedInstance = nil;

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

+ (NSArray *)imageUnfilteredFileTypes;
{
	return [NSArray arrayWithObjects:
		@"tif",
		@"tiff",
		@"TIFF",
		@"TIF",
		nil];
}

+ (BOOL)canInitWithData:(NSData *)data
{
	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)
	};
	BOOL canRead = NO;

	NSParameterAssert(data);

	if([data length] < 4)
		return NO;
	
	[data getBytes:header length:4]; 

	for(index = 0; index < 11;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);
	}

	return canRead;
}


- (NSBitmapImageRep *)decodeFromData:(NSData *)data
{
	NSBitmapImageRep *tiffRep;


	_SDFlags.lastCorrupt = NO;
	
	if(![[self class] canInitWithData:data]) {
		VERBOSE {
			METHOD;
			NSLog(@"+canInitWithData: returned NO");
		}
		_SDFlags.lastCorrupt = YES;
		return nil;
	} else	VERBOSE {
		METHOD;
		NSLog(@"Data validated");
	}


	// decode image
	tiffRep = [NSBitmapImageRep imageRepWithData:data];

	VERBOSE {
		METHOD;
		NSLog(@"Image was %s corrupted.",
				_SDFlags.lastCorrupt ? "" : "not");
	}

	return tiffRep; 
}

@end


