/*
  */

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


unsigned char keym[100];
unsigned char kon=0;
unsigned kbdpowoff;

#define YES 1
#define NO 0
#define NM 14


void keyinit()
{
    int i;

    for (i = 0; i < 100; i++) {
	keym[i] = 0;
    }
    kbdpowoff = NO;
}


#define BRK 0x03		/* ctrl-C */
#define CLR 0x0c
#define UP  0x10
#define DN  0x0e
#define LA  0x02
#define RA  0x06
#define RET 0x0d
#define NUL 0xff
#define KEOF 0x04
#define BS  0x08
#define DEL 0x7f

static char scandef[] = {
/*	+0	+1	+2	+3	+4	+5	+6	+7   */
	'7',	'8',	'9',	'/',	'>',	NUL,	NUL,	NUL,
	'4',	'5',	'6',	'*',	'<',	'U',	'D',	'M',
	'1',	'2',	'3',	'-',	'P',	'q',	'a',	'z',
	'0',	'%',	'.',	'+',	'=',	'w',	's',	'x',
	'H',	'S',	'C',	'T',	'K',	'e',	'd',	'c',
	'X',	'G',	'N',	'L',	'[',	'r',	'f',	'v',
	'E',	'^',	'R',	'Q',	'\\',	't',	'g',	'b',
	NUL,	CLR,	'|',	'F',	DN,	'y',	'h',	'n',
	NUL,	NUL,	')',	'I',	UP,	'u',	'j',	'm',
	NUL,	NUL,	NUL,	'(',	LA,	'i',	'k',	' ',
	NUL,	NUL,	NUL,	NUL,	RA,	'o',	'l',	RET,
	NUL,	NUL,	NUL,	NUL,	NUL,	'p',	',',	'B',
	NUL,	NUL,	NUL,	NUL,	NUL,	NUL,	'Z',	'A',
	NUL,	NUL,	NUL,	NUL,	NUL,	NUL,	NUL,	KEOF
};


int keyscan(int ch)
{
    int i, j;

    if ((ch == BS) || (ch == DEL)) {
	ch = LA;	/* バックスペースを左矢印にマッピング */
    }
    kon = NO;
    for (i = 0; i < NM; i++) {
	keym[i] = 0;
    }
    for (i = 0; i < NM; i++) {
	for (j = 0; j < 8; j++) {
	    if (ch == scandef[i * 8 + j]) {
		keym[i] = (1 << j);
		break;
	    }
	}
	if (keym[i] != 0) {
	    break;
	}
    }
    if (ch == BRK) {
	kon = YES;
    }
    if (ch == KEOF) {
	kbdpowoff = YES;
    }
    return(ch);
}


void scaninit()
{
    int i;

    for (i = 0; i < NM; i++) {
	keym[i] = 0;
    }
    kon = 0;
}


void showkeytab()
{
    printf("\n*KEY BINDINGS* (PC -> Your terminal)\r\n\n");
    printf("0..9, +-*/, A..Z, SPC, ',' -> 0..9, +-*/, a..z, SPC, ','\r\n");
    printf("hyp,  sin,  cos,  tan,  F-E,   C/CE  -> H, S, C, T, F, ^L\r\n");
    printf("HEX,  DEG,  ln,   log,  1/x,   STAT  -> X, G ,N, L, I, | \r\n");
    printf("EXP,  x^y,  SQRT, x^2,  (,     )     -> E, ^, R, Q, (, ) \r\n");
    printf("x->M, RM,   M+,   +/-,  '.',   =     -> >, <, P, %%,'.',= \r\n");
    printf("CAL,  BASIC,SHIFT,DEF,  SML,   SHIFT -> A, B, Z, D, M, U \r\n");
    printf("UP,   DOWN, LEFT, RIGHT              -> ^P,^N,^F,^B\r\n");
    printf("Kana, Ten, cho-on,BRK,  ENTER        -> K, [, \\, ^C,^M\r\n");
    printf("POWER OFF -> ^D\r\n");
}

