/*
 *  FILE: inputhand.c
 *  Support routines for installing/removing an input handler.
 *
 *  Public Domain, but keep my name in it as the original author.
 *  31-Oct-88	Jan Sven Trabandt   added to gimme.lib
 */


#define I_AM_INPUTHAND
#include "gimmelib/gimmefuncs.h"


struct IOStdReq *addInputHandler( handler, data, pri, name )
    void    (*handler)();
    APTR    data;
    BYTE    pri;
    UBYTE   *name;
{
    struct MsgPort	*port;
    struct IOStdReq	*ioreq;
    struct Interrupt	*handint;

#ifdef GIMME_WIMPY
    if( !handler ) {
	return( NULL );
    }
#endif
    if( !(port = CreatePort(NULL, 0L)) ) {
	return( NULL );
    }
    if( !(ioreq = CreateStdIO(port)) ) {
	DeletePort( port );
	return( NULL );
    }
    if( !(handint = AllocMem((ULONG)sizeof(struct Interrupt),
				MEMF_PUBLIC | MEMF_CLEAR)) ) {
	DeleteStdIO( ioreq );
	DeletePort( port );
	return( NULL );
    }
    handint->is_Data = data;
    handint->is_Code = handler;
    handint->is_Node.ln_Type = NT_MESSAGE;
    handint->is_Node.ln_Pri = pri;
    handint->is_Node.ln_Name = (char *) name;
    if( OpenDevice("input.device", 0L, ioreq, 0L) ) {
	FreeMem( handint, (ULONG)sizeof(struct Interrupt) );
	DeleteStdIO( ioreq );
	DeletePort( port );
	return( NULL );
    }
    ioreq->io_Command = IND_ADDHANDLER;
    ioreq->io_Data = (APTR) handint;
    ioreq->io_Length = sizeof(struct Interrupt);
    if( DoIO(ioreq) ) {
	CloseDevice( ioreq );
	FreeMem( handint, (ULONG)sizeof(struct Interrupt) );
	DeleteStdIO( ioreq );
	DeletePort( port );
	return( NULL );
    }
    return( ioreq );
} /* addInputHandler */


short removeInputHandler( ioreq )
    struct IOStdReq *ioreq;
{
#ifdef GIMME_WIMPY
    if( !ioreq ) {
	return( -1 );
    }
#endif
    ioreq->io_Command = IND_REMHANDLER;
    ioreq->io_Message.mn_Node.ln_Type = NT_MESSAGE;
    if( DoIO(ioreq) ) {
	return( -1 );
    }
    CloseDevice( ioreq );
    FreeMem( ioreq->io_Data, (ULONG)sizeof(struct Interrupt) );
    DeletePort( ioreq->io_Message.mn_ReplyPort );
    DeleteStdIO( ioreq );
    return( 0 );
} /* removeInputHandler */
