#import <appkit/publicWraps.h>
#import <appkit/Application.h>
#import <appkit/NXImage.h>
#import <appkit/Pasteboard.h>
#import <appkit/Listener.h>
#import <appkit/nextstd.h>
#import <appkit/errors.h>
#import <stdio.h>
#import <stdlib.h>
#import <string.h>
#import <libc.h>
#import <sys/types.h>
#import "TVController.h"
#import "ToyWin.h"
#import "strfunc.h"
#import "common.h"

/*  Program by T. Ogihara
    This code is based on:
	GIFFilter.m, Graphics Interchange Format (GIF) image filter service.
	Author: Michael McCulloch
*/

@implementation TVController (PBService)

extern const char **fileTypeBuffer;
extern short *fileTypeIDBuffer;


- convertToTIFF:pasteboard userData:(const char *)userData 
          error:(char **)errorMessage
{
	int i;
	NXAtom currentType;
	char *data;
	int dataLen;
	char filename[MAXFILENAMELEN];
	NXStream *tiffStream;
	static int numTypes = 0;
	static NXAtom *convTypes = NULL;

	if(!numTypes){
		for (i = 0; fileTypeBuffer[i]; i++) ;
		convTypes = (NXAtom *)malloc(sizeof(NXAtom) * i);
		for (i = 0, numTypes = 0; fileTypeBuffer[i]; i++) {
		    if (fileTypeIDBuffer[i] != Type_tiff
				&& fileTypeIDBuffer[i] != Type_eps)
			convTypes[numTypes++]
			    = NXCreateFilenamePboardType(fileTypeBuffer[i]);
		}
		convTypes[numTypes] = NULL;
	}

	currentType = [pasteboard findAvailableTypeFrom:convTypes num:numTypes];
	if (!currentType)
		return self;
	[pasteboard readType:currentType data:&data length:&dataLen];
	if(!data || dataLen <= 0)
		return self;
	/* Get the first name of the file list... */
	for (i = 0; i < dataLen; i++) {
		if (data[i] == 0 || data[i] == '\t') {
			filename[i] = 0;
			break;
		}
		filename[i] = data[i];
	}
	// Deallocate the file name list
	[pasteboard deallocatePasteboardData:data length:dataLen];

	if ((i = getExtension(filename)) == 0)
		return self; /* No Extension */
	if (access(filename, R_OK) != 0)
		return self;
	tiffStream = [self openStreamFromFile:filename : &filename[i]];
	if (tiffStream == NULL)
		return self;

    NX_DURING
	[pasteboard declareTypes:&NXTIFFPboardType num:1 owner:self];
	[pasteboard writeType:NXTIFFPboardType fromStream:tiffStream];
    NX_HANDLER
	NXLogError("Error occurred while converting file %s:",filename);
	NXReportError(&NXLocalHandler);
    NX_ENDHANDLER

	NXCloseMemory(tiffStream, NX_FREEBUFFER);
	return self;
}

@end
