#import "ADSlave.h"
#import "../ADController.h"
#import "../TVController.h"
#import "../ToyWin.h"
#import "../common.h"
#import "../strfunc.h"

#define  WinBufSIZE	4

static id windowBuffer[WinBufSIZE];
static int	wbp = 0;

@implementation ADSlave

- init:sender with:controller dir:(const char *)path
{
	adCtrl = sender;
	tvCtrl = controller;
	directory = str_dup(path);
	return self;
}

- free
{
	free((void *)directory);
	[super free];
	return nil;
}

/* Local Method */
- doNextImage: sender
{
	const char *nextfile;
	char	fn[MAXFILENAMELEN];
	id	tw, oldtw, win;
	int	n;
	BOOL	fixpos, oldflag = NO;

	if ((nextfile = [adCtrl nextFilename]) == NULL)
		return nil;
	sprintf(fn, "%s/%s", directory, nextfile);
	if ([tvCtrl isOpened: fn]) /* already opened */
		return self;
	n = getExtension(nextfile);
	fixpos = [adCtrl scanFixPosition];
	if (fixpos)
		oldflag = [ToyWin displayOverKeyWindow: YES];
	tw = [tvCtrl drawFile: fn : &nextfile[n]];
	if (fixpos)
		(void)[ToyWin displayOverKeyWindow: oldflag];
	if (tw) {
		oldtw = windowBuffer[wbp];
		if (tw != oldtw /* coincidental */
		&& oldtw != nil && [tvCtrl checkWindow:oldtw delete:NO]) {
			win = [oldtw window];
			if ([win counterpart] == nil)
				/* has not been miniaturized */
				[win performClose: self];
		}
		windowBuffer[wbp] = tw;
		wbp = (wbp + 1) % WinBufSIZE;
	}
	return self;
}

- donext: sender
{
	id r = [self doNextImage: sender];
	[adCtrl continueLoop:(r != nil)];
	return r;
}

- dostep: sender
{
	id r = [self doNextImage: sender];
	[adCtrl continueLoop: NO];
	return r;
}

@end
