#include <exec/types.h>
#include <devices/input.h>
#include <exec/execbase.h>
#include <exec/interrupts.h>
#include <exec/io.h>
#include <graphics/clip.h>
#include <graphics/layers.h>
#include <intuition/intuition.h>
#include <intuition/intuitionbase.h>
#include <intuition/screens.h>
#include <proto/exec.h>
#include <proto/intuition.h>
#include <proto/layers.h>

long _stack = 4000;
char *_procname = "WTF";
long _priority = 0;
long _BackGroundIO = 0;

extern struct ExecBase *SysBase;
struct IntuitionBase *IntuitionBase;
struct Library *LayersBase;

struct MsgPort *InputPort;
struct IOStdReq *InputReq;
struct Interrupt Handler;

extern struct MsgPort *CreatePort();
extern void DeletePort();
extern struct IOStdReq *CreateStdIO();
extern void DeleteStdIO();

extern struct InputEvent *KHandler();

struct
{
	struct Task *TaskAddr;
	BYTE Signal;
} Common;


struct NewWindow WindowDef =
{
	20,30,
	160,10,
	-1,-1,
	CLOSEWINDOW,
	WINDOWDRAG|WINDOWDEPTH|WINDOWCLOSE|SIMPLE_REFRESH|ACTIVATE,
	NULL,
	NULL,
	"WTF",
	NULL,
	NULL,
	0,0,
	0,0,
	WBENCHSCREEN
};
struct Window *WTFWindow;
ULONG SigMask;


int CXBRK()

{
	return(0);
}


void OpenAll()

{
	void CloseAll();
	
	if (!(IntuitionBase = (struct IntuitionBase *) OpenLibrary("intuition.library",0L)))  CloseAll();
	if (!(LayersBase = OpenLibrary("layers.library",0L)))  CloseAll();
	
	if ((Common.Signal = AllocSignal(-1L)) == -1)  CloseAll();
	Common.TaskAddr = SysBase->ThisTask;
	
	if (!(InputPort = CreatePort(NULL,0)))  CloseAll();
	if (!(InputReq = CreateStdIO(InputPort)))  CloseAll();
	if (OpenDevice("input.device",0,(struct IORequest *) InputReq,0))  CloseAll();
	Handler.is_Node.ln_Pri = 51;
	Handler.is_Node.ln_Name = "WTF_Input_Handler";
	Handler.is_Code = (void (*)) KHandler;
	InputReq->io_Command = IND_ADDHANDLER;
	InputReq->io_Data = (APTR) &Handler;
	SendIO((struct IORequest *) InputReq);
	
	if (!(WTFWindow = OpenWindow(&WindowDef)))  CloseAll();
	
	SigMask = 1 << Common.Signal | 1 << WTFWindow->UserPort->mp_SigBit;
}


void CloseAll()

{
	if (WTFWindow)  CloseWindow(WTFWindow);
	
	if (InputReq->io_Command)
	{
		InputReq->io_Command = IND_REMHANDLER;
		InputReq->io_Data = (APTR) &Handler;
		DoIO((struct IORequest *) InputReq);
		CloseDevice((struct IORequest *) InputReq);
	};
	if (InputReq) DeleteStdIO(InputReq);
	if (InputPort) DeletePort(InputPort);
	
	if (Common.Signal)  FreeSignal(Common.Signal);
	
	if (LayersBase)  CloseLibrary(LayersBase);
	if (IntuitionBase)  CloseLibrary((struct Library *) IntuitionBase);
	
	exit(0);
}


void _main()

{
	struct Screen *WdScreen;
	struct Layer_Info *li;
	struct Layer *ly;
	WORD xPos, yPos;
	
	OpenAll();
	
	FOREVER
	{
		if (Wait(SigMask) == 1 << Common.Signal)
			{
				Forbid();
				
				WdScreen = IntuitionBase->ActiveScreen;
				xPos = WdScreen->MouseX; yPos = WdScreen->MouseY;
				li = &WdScreen->LayerInfo;
				if (ly = WhichLayer(li,xPos,yPos))
					WindowToFront((struct Window *) ly->Window);
					
				Permit();
			}
			else
				CloseAll();
	};
}

