/**********************************
*
* key.c -- ver 1.0
*
*	Mar 25,2000 ROYALPANDA
*
**********************************/

#include<stdio.h>
#include<X11/Xlib.h>
#include"key.h"

static int KeyTable[256];
static int KeyState;


void KEY_init( void )
{
	int i;

	for( i = 0 ; i < 256 ; i++ )
		KeyTable[i] = 0;

	for( i = 0 ; i < NUM_KEYS ; i++ )
		KeyState = 0;
}


static void add( Display *d, int key, char *keysym_name )
{
	KeySym sym;
	KeyCode code;

	sym = XStringToKeysym(keysym_name);
	if( sym == NoSymbol ){
		fprintf(stderr,"KeySym '%s' does not exist.\n");
		return;
	}
	code = XKeysymToKeycode(d,sym);
	if( code == 0 ){
		fprintf(stderr,"KeySym '%s' is not defined for any KeyCode.\n");
		return;
	}
	KeyTable[code] |= key;
}


void KEY_add( Display *d, int key, char *str )
{
	char buf[256];
	char *p;
	int i;

	if( str == NULL )
		return;

	do{
		p = buf;
		i = 0;
		while( *str && *str != ',' && i < 255 ){
			*p++ = *str++;
			i++;
		}
		*p = '\0';
		add(d,key,buf);
	}while( *str++ );
}


int KEY_change( int keycode, int state )
{
	int key;

	key = KeyTable[keycode];

	if( state )
		KeyState |= key;
	else
		KeyState &= ~key;

	return key;
}


int KEY_read( void )
{
	return KeyState;
}
