/* av.c -- autopoint2 voodoo	*/

#include "sysall.h"

struct IntuitionBase *IntuitionBase = NULL;
struct Library	*LayersBase = NULL;

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

apt2_shutdown()
{
	if (IntuitionBase) CloseLibrary((struct Library *)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);
}
