/* $Id: rkcv.c,v 1.2 92/09/01 20:20:16 tf Exp $ © Tobias Ferber */

#include <exec/types.h>
#include <exec/devices.h>
#include <exec/ports.h>
#include <exec/io.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <devices/console.h>
#include <devices/inputevent.h>

/*
 *   This stuff down here handles the raw key conversion stuff
 *   properly.  Thanks to Willy Langeveld and Carolyn Scheppner.
 */

int dos_rkcv(),
    dos_rkcvinit(),
    dos_rkcvexit();

struct IOStdReq ConStdReq;
long ConsoleDevice;

/*
 * FUNCTION
 *
 *  dos_rkcv() -- convert raw key to ascii string.
 *
 * SYNOPSIS
 *
 *   actual = dos_rkcv(code, buffer, length);
 *
 * DESCRIPTION
 *
 *  Covert raw key number to array of console device ascii text
 *  using the default keymap.
 *
 * INPUTS
 *
 *  int code        Raw key number.
 *  int qual        Qualifier.
 *  char *buffer    Pointer to an array of char to receive the
 *                  conversion.
 *  int length      length of buffer.
 *
 * OUTPUTS
 *
 *  int actual      #of chars in the buffer
 *
 */
int dos_rkcv(code, qual, buffer, length)
int code;
int qual;
char *buffer;
int length;
{
   int actual;

   static struct InputEvent event;

   event.ie_Class = IECLASS_RAWKEY;
   event.ie_Code = code;
   event.ie_Qualifier = qual;

   actual = RawKeyConvert(&event, buffer, (long) length, NULL);

   if(actual < 0) actual = 0;
   buffer[actual] = '\0';

   return(actual);
}


/*
 * FUNCTION
 *
 *  dos_rkcvinit() -- open stuff for dos_rkcv().
 *
 * SYNOPSIS
 *
 *   error = dos_rkcvinit();
 *
 * DESCRIPTION
 *
 *  Open the Console device for later use with dos_rkcv().
 *
 * INPUTS
 *
 *  None
 *
 * OUTPUTS
 *
 *  F. value: 1 on faliure, zero otherwise.
 *
 */
int dos_rkcvinit()
{
   if (OpenDevice("console.device", -1L, &ConStdReq, 0L) != NULL) {
      ConsoleDevice = 0L;
      return(1);
   }
   else {
      ConsoleDevice = (long) ConStdReq.io_Device;
      return(0);
   }
}


/*
 * FUNCTION
 *
 *  dos_rkcvexit() -- close stuff for dos_rkcv().
 *
 * SYNOPSIS
 *
 *   error = dos_rkcvexit();
 *
 * DESCRIPTION
 *
 *  Close the Console device after use with dos_rkcv().
 *
 * INPUTS
 *
 *  None
 *
 * OUTPUTS
 *
 *  F. value:  Always zero;
 *
 */
int dos_rkcvexit()
{
   if (ConsoleDevice) CloseDevice(&ConStdReq);
   return(0);
}
