#include    <stdio.h>
#include    <ctype.h>
#include    <kkstr2.h>
#include    "defs.h"

#define	MAX_MAC	512

extern char	*Act_vram();
extern void	wrtstr();
extern void	memcpy();
extern void	memset();
extern int	strlen();
extern void	locate();
extern char	*SPCSTR;

short  ReWrt_flg=FALSE;

static struct _MACRO {
       int      mc_ch;
       unsigned mc_ec;
    } mac_key[MAX_MAC+1];
static int	mac_cnt=0;
static int	mac_max=0;
static int	mac_flg=0;

static int   	ch_bak;
static unsigned ec_bak;
static int   	hit_flg=FALSE;

void	Tango_Touroku(char *str)
{
    int     x;
    char    *vp;

    memset(str,80,0);
    vp = (char *)Act_vram();
    for ( x = Cur_X ; x < 80 ; x++ ) {
	if ( (unsigned char)(*(str++) = *(vp+1)) < ' ' )
	    *(str-1) = ' ';
	vp += 2;
    }
}

void	mac_save()
{
    switch(mac_flg) {
    case 0: case 2:
	mac_flg = 1;
	mac_max = 0;
	wrtstr("只今キ−マクロを定義中です",30,1,0x15);
	break;
    case 1:
	mac_flg = 2;
	mac_cnt = 0;
	mac_max--;
	wrtstr(SPCSTR,30,1,0x1F);
	break;
    }
}
void	mac_go()
{
    if ( mac_flg == 2 ) {
	mac_flg = 3;
	mac_cnt = 0;
    }
}
int	kbhit()
{
    if ( hit_flg != FALSE )
	return 1;

    if ( mac_flg == 3 ) {
	if ( mac_cnt < mac_max ) {
	    hit_flg = TRUE;
	    ch_bak = mac_key[mac_cnt].mc_ch;
	    ec_bak = mac_key[mac_cnt].mc_ec;
	    mac_cnt++;
	    return 1;
	} else {
	    mac_flg = 2;
	    mac_cnt = 0;
	}
    }

  do {
    while ( (ch_bak = KYB_read(1,&ec_bak)) != 0xFFFF ) {
	if ( ch_bak & 0x8000 || (ec_bak & 0xFF00) > 0x5100 )
	    ch_bak = 0xFFFF;
	switch(ec_bak & 0xFF00) {
	case 0xFF00:
	    break;

	default:
	    hit_flg = TRUE;
	    if ( mac_flg == 1 && mac_max < MAX_MAC ) {
		mac_key[mac_max].mc_ch = ch_bak;
		mac_key[mac_max].mc_ec = ec_bak;
		mac_max++;
	    }
	    return 1;
	}
    }
  } while ( KAN_inpchk() == KAN_MISET );

    return 0;
}
int	Get_key(ec)
unsigned *ec;
{
    while ( kbhit() == 0 );
    hit_flg = FALSE;
    *ec = ec_bak & 0xFF14;
    return ch_bak;
}
int	getch()
{
    int       ch;
    unsigned  ec;

    while ( (ch = Get_key(&ec)) == 0xFFFF );
    return ch;
}
