/*-
 * Copyright (c) 2000
 * Tatsuya Kudoh(CDR/TK),ROYALPANDA.    All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
#include<stdlib.h>
#include<sys/bios.h>


#define INTENSITY	10

static int Key_right;
static int Key_left;
static int Key_up;
static int Key_down;

static int Key_center;
static int Key_cancel;


static int Dir_table[16] = {
		/* LDRU */
	4,	/* 0000 */
	1,	/* 0001 */
	5,	/* 0010 */
	2,	/* 0011 */
	7,	/* 0100 */
	4,	/* 0101 */
	8,	/* 0110 */
	5,	/* 0111 */
	3,	/* 1000 */
	0,	/* 1001 */
	4,	/* 1010 */
	1,	/* 1011 */
	6,	/* 1100 */
	3,	/* 1101 */
	7,	/* 1110 */
	4,	/* 1111 */
};


void KEY_clear( void )
{
	Key_right = 0;
	Key_left = 0;
	Key_up = 0;
	Key_down = 0;
}


int KEY_read( unsigned k )
{
	unsigned s;

	if( k & KEY_UP1 )
		Key_up = INTENSITY;
	else if( Key_up )
		Key_up--;

	if( k & KEY_DOWN1 )
		Key_down = INTENSITY;
	else if( Key_down )
		Key_down--;

	if( k & KEY_RIGHT1 )
		Key_right = INTENSITY;
	else if( Key_right )
		Key_right--;

	if( k & KEY_LEFT1 )
		Key_left = INTENSITY;
	else if( Key_left )
		Key_left--;

	s = 0;
	if( Key_up )
		s |= 1;
	if( Key_right )
		s |= 2;
	if( Key_down )
		s |= 4;
	if( Key_left )
		s |= 8;

	s = Dir_table[s];

	if( k & KEY_A ){
		if( Key_center == 0 ){
			s |= 16;
			Key_center = 1;
		}
	}else{
		Key_center = 0;
	}

	if( k & KEY_B  ){
		if( Key_cancel == 0 ){
			s |= 32;
			Key_cancel = 1;
		}
	}else{
		Key_cancel = 0;
	}

	return s;
}
