#import "../ImageOpr.h"
#import <appkit/Application.h>
#import <appkit/publicWraps.h>
#import <appkit/NXBitmapImageRep.h>
#import <appkit/Control.h>
#import <appkit/Panel.h>
#import <appkit/TextField.h>
#import <stdio.h>
#import <stdlib.h>
#import <string.h>
#import <libc.h>
#import <streams/streams.h>
#import "../TVController.h"
#import "../ToyWin.h"
#import "../ToyWinEPS.h"
#import "../ToyView.h"
#import "../common.h"
#import "../getpixel.h"
#import "imageOperation.h"


@implementation ImageOpr (Newmap)

- newBitmap: sender
{
	ToyWin	*tw, *newtw = nil;
	ToyView	*tv = NULL;
	commonInfo	*cinf;
	char	fn[256];
	const char *fnam;
	int err;

	if ((tw = [theController keyWindow]) == nil) {
		NXBeep();
		return self;
	}
	tv = [tw toyView];
	cinf = [tv commonInfo];
	fnam = [tw filename];
	sprintf(fn, "%s(Bitmap)", fnam);

	if (cinf->type == Type_eps) {
		NXStream *stream = [(ToyWinEPS *)tw openTiffStream:NO];
		if (stream == NULL) {
			errAlert(fnam, Err_MEMORY);
			return self;
		}
		newtw = [[ToyWin alloc] init:tw by:NewBitmap];
		err = [newtw drawFromFile:(const char *)fn or:stream];
		NXCloseMemory(stream, NX_FREEBUFFER);
		if (err) {
			errAlert(fnam, err);
			[newtw free];
			return self;
		}
	}else {
		NXBitmapImageRep *rep;
		commonInfo *newinf;
		unsigned char *map[MAXPLANE], *newmap[MAXPLANE];
		float factor = [tv scaleFactor];
		if (factor == 1.0) {
			warnAlert(fnam, Err_OPR_IMPL);
			return self;
		}
		rep = (NXBitmapImageRep *)[[tv image] bestRepresentation];
		[rep getDataPlanes: map];
		newinf = makeResizedMap(factor, cinf, map, newmap);
		if (newinf == NULL) {
			warnAlert(fnam, Err_MEMORY);
			return self;
		}
		newtw = [[ToyWin alloc] init:tw by:NewBitmap];
		[newtw initLocateWindow:fn
			width:newinf->width height:newinf->height];
		[newtw makeComment: newinf from: cinf];
		[newtw drawView:newmap info: newinf];
	}
	[theController newWindow: newtw];
	return self;
}


- EPSResize: sender
{
	ToyWin	*tw, *newtw = nil;
	ToyView	*tv = NULL;
	NXStream *stream;
	commonInfo	*cinf;
	char	fn[256];
	const char *fnam;
	int err;

	if ((tw = [theController keyWindow]) == nil
	|| [(tv = [tw toyView]) scaleFactor] == 1.0) {
		NXBeep();
		return self;
	}
	cinf = [tv commonInfo];
	fnam = [tw filename];
	sprintf(fn, "%s(ResizeEPS)", fnam);

	if (cinf->type != Type_eps) {
		errAlert(fnam, Err_EPS_ONLY);
		return self;
	}

	stream = [(ToyWinEPS *)tw resizeEPS:[tv scaleFactor] name:fn error:&err];
	if (stream == NULL) {
		errAlert(fnam, err);
		return self;
	}
	newtw = [[ToyWinEPS alloc] init:tw by:ResizeEPS];
	err = [newtw drawFromFile:(const char *)fn or:stream];
	NXCloseMemory(stream, NX_FREEBUFFER);
	if (err) {
		errAlert(fnam, err);
		[newtw free];
		return self;
	}
	[theController newWindow: newtw];
	return self;
}

@end
