/******************************************************************************
**
**		KEY.LIB << MSC V5.1 >>
**
**		<HISTORY>
**		1990.07.03 : CREATE
**
**		Programmed by Y.HIRATA Nifty-ID (NAB03321)
**
******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>
#include <conio.h>
#include "kyb.h"

/****************************  10us 単位でのWAIT  ****************************/
void soft_time( unsigned short waitcount )
{
	union	REGS	regs ;

	regs.x.cx = waitcount ;

	int86( 0xFD,&regs,&regs ) ;

	return ;
}

/******************************************************************************
	KEY_read : 一文字入力(キーボード)
	< RETURN >
	文字コード, 入力なしの場合には 0 を返す｡
******************************************************************************/
unsigned	KEY_read( waitsw, encode )
unsigned	waitsw ;	/*  キー入力待ち指定 : 0 - 入力待ち				*/
						/*					 : 1 - 入力待ちなし			*/
unsigned	*encode ;	/*  エンコード情報								*/
{
	union	REGS	regs ;

	regs.h.ah = 0x09 ;
	regs.h.al = waitsw ;

	int86( KEY_INT,&regs,&regs ) ;

	if ( regs.h.ah==0x00 ) {
		if ( regs.h.dh==0xff ) {			/*  入力文字なし	*/
			*encode = 0 ;
			return(0) ;
		} else {							/*  入力文字あり	*/
			*encode = regs.x.bx ;
			return( regs.h.dl ) ;
		}
	}
	*encode = 0 ;
	return(0) ;
}

/******************************************************************************
	KEY_matrix : マトリクス入力
******************************************************************************/
int		KEY_matrix( matrix )
char	*matrix ;		/*  マトリクス情報( 16 ﾊﾞｲﾄ )					*/
{
	union	REGS	regs ;
	struct	SREGS	sregs ;
	char	matx[16] ;

	regs.h.ah = 0x0A ;
	regs.h.al = 0x00 ;
	regs.x.di = (unsigned int)matx ;

	segread( &sregs ) ;
	int86x( KEY_INT,&regs,&regs,&sregs ) ;

	memcpy( matrix,matx,16 ) ;

	return( regs.h.ah ) ;
}

/******************************************************************************
	KEY_test : マトリクスからキーが押されているかどうかをチェックする。
******************************************************************************/
int		KEY_test( matrix,keyadrs )
char	*matrix ;		/*  マトリクス情報( 16 ﾊﾞｲﾄ )					*/
char	keyadrs ;		/*  キーアドレス								*/
{
	unsigned char	testbit ;
	int		c ;

	testbit = 0x01 ;
	for ( c=0; c<(keyadrs%8); c++ ) testbit <<= 1 ;
	if ( (matrix[keyadrs/8] & testbit) == testbit ) return( TRUE ) ;

	return( FALSE ) ;
}

/******************************************************************************
	KEY_bufcls : バッファクリア
******************************************************************************/
int		KEY_bufcls()
{
	union	REGS	regs ;

	regs.h.ah = 0x06 ;
	regs.h.al = 0x00 ;

	int86( KEY_INT,&regs,&regs ) ;

	return( regs.h.ah ) ;
}

/***************************  ^C を受け付けない入力  *************************/
int inkey()
{
	return( bdos(6,0xFF,0x00) & 0x00ff ) ;
}

