/*
	sel_menu.c
	カーソルによる選択メニュー 汎用
	1994/02/27
*/

#include <stdio.h>

#ifdef TOWNS
unsigned char getop( void );			/* パッド & キーBIOS */
#else
#define getop getch
#endif

#define LEFT (29)
#define RIGHT (28)
#define UP (30)
#define DOWN (31)
#define EXEC (18)
#define QUIT (17)
#define ESCKEY (0x1b)

#define ESC "\x1b["
#define NOM "0m"
#define REV "7m"

#define ON 1
#define OFF 0

char us[30];

void locdisp(int x,int w,int firstline,char a,char *s){
	if( a=='R' ) cputs(ESC REV);
	else
	if( a=='N' ) cputs(ESC NOM);
	else return;
	cprintf(us,firstline+(x/w),(x%w)*(80/w),s);
}

int sel_menu( int w, int firstline, char *word[] ){/* 選択メニュー */
	/* w: 横並びの数 */
	/* firstline: 表示開始行 */
	/* word: 選択項目のポインタ */
	int m,i,b;
	char endf=OFF; /* メニュー終了フラグ */

	/* 出力書式の設定 */
	sprintf(us,ESC"%%d;%%df[%%-%d.%ds]",80/w-5,80/w-5);

	/* firstline 以降の消去 */
	cprintf(ESC"%d;0f"ESC"0J",firstline);

	/* 選択肢の表示 */
	for(m=0;word[m][0]!=NULL;m++)
		locdisp(m,w,firstline,'N',word[m]); /* m : 選択肢の数 */

	i=b=0;
	/* カーソル選択 */
	while(endf==OFF){
		locdisp(b,w,firstline,'N',word[b]);
		locdisp(i,w,firstline,'R',word[i]);
		b = i;
		switch (getop()) {
		case LEFT: /* カーソル ← */
			i = (i+m-1) % m;
			break;
		case RIGHT: /* カーソル → */
			i = (i+1) % m;
			break;
		case UP: /* カーソル ↑ */
			i = (i+m-w) % m;
			break;
		case DOWN: /* カーソル ↓ */
			i = (i+w) % m;
			break;
		case EXEC: /* 実行 key */
		case 0x0d: /* RETkey */
			endf=ON;
			break;
		case QUIT: /* 取消 key */
		case ESCKEY: /* ESC key */
			cputs(ESC"37;0m");
			return -1; /* 取り止め */
		default: ;
		} /* switch */
	} /* while(endf==OFF) */
	locdisp(i,w,firstline,'N',word[i]);
	return i;
}
