#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include "Converter.h"

#define False 0
#define True 1

typedef unsigned char *MString;
typedef unsigned char *XPointer;

static KeySym getX11KeySym(long awtKey)
{
    int i;
    for (i = 0; keymapTable[i].awtKey != 0; i++) {
        if (keymapTable[i].awtKey == awtKey) {
            return keymapTable[i].x11Key;
        }
    }
    return 0;
}

modifyEvent(long *keyCode, unsigned short *keyChar, long *State)
{
    KeySym keysym = 0;
    long state = 0;
#ifndef NDEBUG
    logf("keycode:0x%x, keychar:0x%x, keystate:0x%x\n", *keyCode, *keyChar, *State);
#endif
    switch(*keyCode) {
      case java_awt_event_KeyEvent_VK_ENTER:
      case java_awt_event_KeyEvent_VK_BACK_SPACE:
      case java_awt_event_KeyEvent_VK_TAB:
      case java_awt_event_KeyEvent_VK_ESCAPE:
      case java_awt_event_KeyEvent_VK_DELETE:
          keysym = getX11KeySym(*keyCode);
          break;
      default:
          if (*keyChar != 0 && *keyChar < 256) {
              keysym = *keyChar;
          } else {
              keysym = getX11KeySym(*keyCode);
          }
          break;
    }
    if (keysym >= 'A' && keysym <= 'Z') {
        state |= ShiftMask;
    }
    if (*State & java_awt_event_InputEvent_SHIFT_MASK) {
        state |= ShiftMask;
    }
    if (*State & java_awt_event_InputEvent_CTRL_MASK) {
        state |= ControlMask;
    }
    if (*State & java_awt_event_InputEvent_META_MASK) {
        state |= awt_MetaMask;
    }
    if (*State & java_awt_event_InputEvent_ALT_MASK) {
        state |= awt_AltMask;
    }

    *keyCode = keysym;
    if((*keyChar < 0x20) || (*keyChar > 0x7E))
	*keyChar = 0xFF;
    if(state != 0) *State = state;
#ifndef NDEBUG
    logf("keycode:0x%x, keychar:0x%x, keystate:0x%x\n", *keyCode, *keyChar, *State);
#endif
}

