/*
	Systems Formulate BUBCOM80 Emulator 'eBUBCOM80'

	Author : Takeda.Toshiya
	Date   : 2018.05.08-

	[ keyboard ]
*/

#include "keyboard.h"

namespace BUBCOM80 {
static const uint8_t key_matrix[128] = {
/*
// keyboard
00:	2	3	4	5	6	7	8	9	0	-	^	\	NUM *	NUM /	NUM +	NUM -
10:	W	E	R	T	Y	U	I	O	P	@	[	RETURN	NUM 7	NUM 8	NUM 9	NUM ,
20:	S	D	F	G	H	J	K	L	;	:	]	A	NUM 4	NUM 5	NUM 6	NUM .
30:	X	C	V	B	N	M	,	.	/	_		Z	NUM 1	NUM 2	NUM 3	
40:	1	Q	TAB	ESC			SPACE	GRAPH	CTRL	KANA	SHIFT	BACK	CAP	NUM 0	NUM 000	NUM RETURN
50:	F1	F2	F3	F4				CLS	EDIT	LIST	RUN			LEFT	DOWN	RIGHT
60:	F5	F6	F7	F8				LABEL	FILES	INIT	STOP			INS	UP	DEL
// joystick #1/#2
70:	TRIG	UP	DOWN	LEFT	RIGHT	TRIG	UP	DOWN	LEFT	RIGHT						

GRAPH	Alt
CLS	Home
EDIT	End
LIST	PgUp
RUN	PgDn
LABEL	F9
FILES	F10
INIT	F11
STOP	F12
*/
	0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0xBD, 0xDE, 0xDC, 0x6A, 0x6F, 0x6B, 0x6D,
	0x57, 0x45, 0x52, 0x54, 0x59, 0x55, 0x49, 0x4F, 0x50, 0xC0, 0xDB, 0x0D, 0x67, 0x68, 0x69, 0x6C,
	0x53, 0x44, 0x46, 0x47, 0x48, 0x4A, 0x4B, 0x4C, 0xBB, 0xBA, 0xDD, 0x41, 0x64, 0x65, 0x66, 0x6E,
	0x58, 0x43, 0x56, 0x42, 0x4E, 0x4D, 0xBC, 0xBE, 0xBF, 0xE2, 0x00, 0x5A, 0x61, 0x62, 0x63, 0x00,
	0x31, 0x51, 0x09, 0x1B, 0x00, 0x00, 0x20, 0x12, 0x11, 0x15, 0x10, 0x08, 0x14, 0x60, 0x00, 0x00,
	0x70, 0x71, 0x72, 0x73, 0x00, 0x00, 0x00, 0x24, 0x23, 0x21, 0x22, 0x00, 0x00, 0x25, 0x28, 0x27,
	0x74, 0x75, 0x76, 0x77, 0x00, 0x00, 0x00, 0x78, 0x79, 0x7A, 0x7B, 0x00, 0x00, 0x2D, 0x26, 0x2E,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

static const uint32_t joy_bits[5] = {
	0xf0, 0x01, 0x02, 0x04, 0x08,	// TRIG, UP, DOWN, LEFT, RIGHT
};

void KEYBOARD::initialize()
{
	key_stat = emu->get_key_buffer();
	joy_stat = emu->get_joy_buffer();
}

uint32_t KEYBOARD::read_io8(uint32_t addr)
{
	switch(addr & 0x7f) {
	case 0x70:
	case 0x71:
	case 0x72:
	case 0x73:
	case 0x74:
		if(joy_stat[0] & joy_bits[addr - 0x70]) {
			return 0xff;
		}
		break;
	case 0x75:
	case 0x76:
	case 0x77:
	case 0x78:
	case 0x79:
		if(joy_stat[1] & joy_bits[addr - 0x75]) {
			return 0xff;
		}
		break;
	default:
		if(key_stat[key_matrix[addr & 0x7f]]) {
			return 0xff;
		}
		break;
	}
	return 0x0f;
}
}
