/*

dmove86 version 2.00c

console.c -- 画面初期設定／基礎処理ルーチン

Copyright (c) 1993,94 Delmonta

*/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<jctype.h>
#include"dmove86.h"

/*--------------------------------1文字入力----------------------------------*/
static	char	Ungetch_buf[16];
static	int	Ungetch_num = 0;

void	dm_ungetch(char c)
{
	Ungetch_buf[Ungetch_num++] = c;
}

char	dm_getch(void)
{
	char	c;

	if	(Ungetch_num)		/* バッファに文字がたまっているか */
		return Ungetch_buf[--Ungetch_num];

rep:
	c = getch();

	if	(c=='\033' && kbhit())	/*  ファンクションキーを読みとばす */
	{
		getch();
		goto rep;
	}
	else if	(c=='\0' && kbhit())	/* IBM PCの特殊キー */
	{
		switch	(getch())
		{
		case 0x48:	c = UPKEY;	break;
		case 0x49:	c = RIGHTKEY;	break;
		case 0x4a:	c = LEFTKEY;	break;
		case 0x4b:	c = DOWNKEY;	break;
		default:	goto rep;
		}
	}
	else
	{
		switch	(c)	/* キャラクタコード変換 */
		{
		case '\n':	c = DOWNKEY;	break;	/* 98→TOWNS         */
		case 'K'-0x40:	c = UPKEY;	break;
		case 'L'-0x40:	c = RIGHTKEY;	break;

		case '\x1d':	c = LEFTKEY;	break;	/* TOWNS→98         */
							/* BSを処理するため  */

		case 'E'-0x40:	c = UPKEY;	break;	/* ﾀﾞｲﾔﾓﾝﾄﾞｶｰｿﾙ      */
		case 'S'-0x40:	c = LEFTKEY;	break;
		case 'D'-0x40:	c = RIGHTKEY;	break;
		case 'X'-0x40:	c = DOWNKEY;	break;
		}
	}

	return c;
}
/*---------------------------------文字列入力--------------------------------*/
int	strinput(char *buf,unsigned len)
{
	int		_ctypebuf[80];
	int		*ctypebuf = _ctypebuf + 1;

	unsigned	l = 0;	/* 入力中の文字列の長さ */
	unsigned	i;
	char		c;

	_ctypebuf[0] = CT_ANK;

	while	((c=*buf)!='\0')
	{
		putchar(c);

		*ctypebuf = chkctype(c,*(ctypebuf-1));

		buf++;
		ctypebuf++;
		l++;
	}

	for	(i=l ; i<len ; i++)
		putchar(' ');

	for	(i=l ; i<len ; i++)
		putchar('\b');

rep:

	c = dm_getch();

	if	(c=='\b' && l)
	{
		do
		{
			printf("\b \b");
			l--;
			buf--;
		} while( *--ctypebuf==CT_KJ2 || *ctypebuf==CT_ILGL);

	}
	else if	(c=='\r' || c=='\033')
	{
		*buf = '\0';

		if	(c=='\r')
			return 1;
		else
			return 0;
	}
	else if	(c>=' ' && l<len)
	{
		*ctypebuf = chkctype(c,*(ctypebuf-1));

		if	(*ctypebuf == CT_KJ1 && l==len-1)
		{			/* バッファの最後に漢字の第1バイトが */
			dm_getch();	/* 来た場合はその漢字全体を捨てる     */
			putchar('\a');
		}
		else
		{
			l++;
			*buf++ = c;
			ctypebuf++;
			putchar(c);
		}
	}
	else		/* コントロールコード */
		putchar('\a');

	goto rep;
}
/*------------------------------エラーメッセージ-----------------------------*/
char	dm_errmes(char *s)
{
	char	c;
	printf("\033[19;1H\033[33m%s\033[37m",s);

	c = dm_getch();

	printf("\033[19;1H\033[2K");
	return c;
}

void	mkscreen(void)
{

	printf( "\033[1v\033[>5h\033[2J\033[0;37m"
		"ディスクファイル並べ替えユーティリティ DMOVE86 Version 2.00c\n"
		"                     Copyright (c) Delmonta all rights reserved, " __DATE__
		"\033[22;1H"
		"↑↓←→:ｶｰｿﾙ移動 ＋−:ﾍﾟｰｼﾞ切替 H/?:ヘルプメッセージ\n");
};
