/* av.c -- autopoint2 voodoo	*/

/*
Copyright (c) 1987, 1988, 1989 Jim Mackraz and I&I Computing.

Executables based on this information may be used in software
for Commodore Amiga computers.  All other rights reserved.
This information is provided "as is"; no warranties are made.
All use is at your own risk, and no liability or responsibility
is assumed.
*/

#include "sysall.h"

#define D(x)	;

struct IntuitionBase *IntuitionBase = NULL;
APTR	LayersBase = NULL;

apt2_init()
{
	IntuitionBase=(struct IntuitionBase *) OpenLibrary("intuition.library",33L);
	if (!IntuitionBase) return (0);
	LayersBase= (APTR) OpenLibrary("layers.library",33L);
	if (!LayersBase) return (0);
	return (1);
}

apt2_shutdown()
{
	if (IntuitionBase) CloseLibrary(IntuitionBase);
	if (LayersBase) CloseLibrary(LayersBase);
}

autopoint2()
{
	LONG 					ilock;
	struct Screen			*screen;
	struct Window			*mousewindow = NULL;
	static struct Window	*lasttry = NULL;
	struct Layer			*layer;


	ilock = LockIBase(0L);

	/* figure out which window mouse is over	*/
	for (screen = IntuitionBase->FirstScreen; screen; screen=screen->NextScreen)
	{
		if (screen->MouseY > 0)		/* this is the ticket	*/
			break;
	}

	if (screen)
	{
		layer = WhichLayer(&screen->LayerInfo,
			(LONG) screen->MouseX, (LONG) screen->MouseY);

		if (layer && (layer != screen->BarLayer) )
	    {
			mousewindow = (struct Window *) layer->Window;
	    }
	}


	/* a number of conditions cause us to wimp out	*/
	if (!mousewindow ||
		(mousewindow == lasttry) ||
		(mousewindow == IntuitionBase->ActiveWindow))
	{
		goto OUT;
	}

	lasttry = mousewindow;
	ActivateWindow(mousewindow);

OUT:
	UnlockIBase(ilock);
}
