struct handlerdata { 
	struct MsgPort mymsgport;
	struct Task *thistask;
	short quit;
	short startrec;
	short stoprec;
	short insert;
	short clear;
	short store;
};

#ifdef DEBUG
void Print(char *string,BOOL newline); /* Print string to _Backstdout */
char *ltoh(char *string,register long val);
extern char string[11];
#endif

void RawInsert(long code,long qualifier);
void RemoveHandler(void);
void InstallHandler(void);

extern void myhandler(void);
extern BPTR _Backstdout;         /* standard output when run in background */
extern struct IOStdReq *inputRequestBlock;
extern struct Interrupt handlerStuff;
extern struct MsgPort *inputDevPort;
extern struct handlerdata data;

void RemoveHandler(void)
{
	if (inputRequestBlock) {
		if (inputRequestBlock->io_Device) {
			inputRequestBlock->io_Command = IND_REMHANDLER;  /* Remove handler */
			inputRequestBlock->io_Data    = (APTR)&handlerStuff;
			DoIO((struct IORequest *)inputRequestBlock);
			CloseDevice((struct IORequest *)inputRequestBlock);
		}
		DeleteStdIO(inputRequestBlock);
	}
	if (inputDevPort) {
		DeletePort(inputDevPort);
	}
	#ifdef DEBUG
	Print("Handler removed",TRUE);
	#endif
	return;
}

void InstallHandler(void)
{
	inputRequestBlock = NULL;
	if (!(inputDevPort = CreatePort(0L, 0L))) {
		RemoveHandler();
	}
	if (!(inputRequestBlock = CreateStdIO(inputDevPort))) {
		RemoveHandler();
	}
	if (OpenDevice("input.device", 0L,(struct IORequest *)inputRequestBlock, 0L)) {
		RemoveHandler();
	}
	handlerStuff.is_Node.ln_Name = "MACRO Handler";
	handlerStuff.is_Data = (APTR)&data;         /* Set up for installation of */
	handlerStuff.is_Code = myhandler;          /* myhandler.                 */
	handlerStuff.is_Node.ln_Pri = 51;         /* Ahead of intuition         */
	inputRequestBlock->io_Command = IND_ADDHANDLER;
	inputRequestBlock->io_Data    = (APTR)&handlerStuff;
	DoIO((struct IORequest *)inputRequestBlock);   /* Add me. */
	#ifdef DEBUG
	Print("Handler installed",TRUE);
	#endif
	return;
}

void RawInsert(long code,long qualifier) {
	/* Set up an input request */
	struct InputEvent MyNewEvent;
	inputRequestBlock->io_Command = IND_WRITEEVENT;
	inputRequestBlock->io_Flags   = 0L;
	inputRequestBlock->io_Length  = (long)sizeof(struct InputEvent);
	inputRequestBlock->io_Data    = (APTR)&MyNewEvent;
	MyNewEvent.ie_Class = IECLASS_RAWKEY; 
	MyNewEvent.ie_Code = code;
	MyNewEvent.ie_Qualifier = qualifier;
	DoIO((struct IORequest *)inputRequestBlock);
}
#ifdef DEBUG
void Print(char *string,BOOL newline) {
	Write(_Backstdout,string,strlen (string));
	if (newline) Write(_Backstdout,"\n",1);
}

char *ltoh(char *string,register long val)
{
	char hex[17] = "0123456789ABCDEF";
	register long count = 9;
  string = "0x00000000";
	while(count>1) {
		string[count] = hex[val%16];
		val >>= 4;
		count--;
	}
	return(string);
}
#endif
