/*************************************************************************
 ***                            KILLWB.C                 (JJB TEMPLAR) ***
 *** Date begun: 4/5/89.                                               ***
 *** Last modified: 4/5/89.                                            ***
 *************************************************************************/
/*** Note: compile with -v option, to disable stack checking.          ***
 *************************************************************************/

#include <exec/types.h>
#include <exec/interrupts.h>
#include <exec/ports.h>
#include <exec/devices.h>
#include <devices/input.h>
#include <devices/inputevent.h>

#include <proto/exec.h>

static struct MsgPort      *inputDevPort;
static struct IOStdReq     *inputRequestBlock;
static struct Interrupt    handlerinfo;
static char                dummy;       /* Not used. */
static int                 handlerthere = 0;

void    killWB(int);

static struct InputEvent __regargs *myhandler(ie,data) /*================*/
struct InputEvent *ie;
char *data;
{
struct InputEvent   *iep,*base,**iepp;
    iep = base = ie;    iepp = &base;

    while (iep) {
        if ((iep->ie_Class == IECLASS_RAWKEY) && (iep->ie_Qualifier & IEQUALIFIER_LCOMMAND)) {
            if ((iep->ie_Code == 0x36) || (iep->ie_Code == 0x37)) {
                *iepp = iep->ie_NextEvent;
            }
            else iepp = &((*iepp)->ie_NextEvent);
        }
        else iepp = &((*iepp)->ie_NextEvent);
        iep = iep->ie_NextEvent;
    }

    return(base);
}

void    killWB(f) /*=====================================================*/
int     f;
{
    if (f && (!handlerthere)) {
        if (!(inputDevPort = CreatePort(0,0))) {
            printf("ERROR: failed to open inputDevPort!\n");
            return;
        }
        if (!(inputRequestBlock = CreateStdIO(inputDevPort))) {
            printf("ERROR: failed to open inputRequestBlock!\n");
            DeletePort(inputDevPort);
            return;
        }
        handlerinfo.is_Data = (APTR)&dummy;
        handlerinfo.is_Code = &myhandler;
        handlerinfo.is_Node.ln_Pri = 51;

        if (OpenDevice("input.device",0,inputRequestBlock,0)) {
            printf("ERROR: failed to open input.device!\n");
            DeleteStdIO(inputRequestBlock);
            DeletePort(inputDevPort);
            return;
        }

        inputRequestBlock->io_Command = IND_ADDHANDLER;
        inputRequestBlock->io_Data = (APTR)&handlerinfo;
        DoIO(inputRequestBlock);
        handlerthere = 1;
    }
    else if ((!f) && handlerthere) {
        inputRequestBlock->io_Command = IND_REMHANDLER;
        inputRequestBlock->io_Data = (APTR)&handlerinfo;
        DoIO(inputRequestBlock);
        CloseDevice(inputRequestBlock);
        DeleteStdIO(inputRequestBlock);
        DeletePort(inputDevPort);
        handlerthere = 0;
    }
}
