#include <smgdef.h>
#include <smg$routines.h>
#include <ssdef.h>
#include "getch2.h"
#include "keycodes.h"

int screen_width=80;
int screen_height=24;
static unsigned int kid=0;

typedef struct {
  int trm;
  int code;
} keycode_st;
static keycode_st getch2_keys[] = {
	SMG$K_TRM_PREV_SCREEN,	KEY_PGUP,
	SMG$K_TRM_NEXT_SCREEN,	KEY_PGDWN,
	SMG$K_TRM_FIND,		KEY_HOME,
	SMG$K_TRM_SELECT,	KEY_END,
	SMG$K_TRM_INSERT_HERE,	KEY_INS,
	SMG$K_TRM_DELETE,	KEY_DEL,
	SMG$K_TRM_BS,		KEY_BS,
	SMG$K_TRM_LEFT,		KEY_LEFT,
	SMG$K_TRM_DOWN,		KEY_DOWN,
	SMG$K_TRM_UP,		KEY_UP,
	SMG$K_TRM_RIGHT,	KEY_RIGHT,
	SMG$K_TRM_KP0,		KEY_F+0,
	SMG$K_TRM_KP1,		KEY_F+1,
	SMG$K_TRM_KP2,		KEY_F+2,
	SMG$K_TRM_KP3,		KEY_F+3,
	SMG$K_TRM_KP4,		KEY_F+4,
	SMG$K_TRM_KP5,		KEY_F+5,
	SMG$K_TRM_KP6,		KEY_F+6,
	SMG$K_TRM_KP7,		KEY_F+7,
	SMG$K_TRM_KP8,		KEY_F+8,
	SMG$K_TRM_KP9,		KEY_F+9,
	SMG$K_TRM_F10,		KEY_F+10,
	0,			0
};

/* Load key definitions from the TERMCAP database. 'termtype' can be NULL */
int load_termcap(char *termtype) {return 0;}

/* Enable and disable STDIN line-buffering */
void getch2_enable()
{
	int status,zero=0;
	status = smg$create_virtual_keyboard(&kid,0,0,0,&zero);
}
void getch2_disable()
{
	if (kid) smg$delete_virtual_keyboard(&kid);
}

/* Read a character or a special key code (see keycodes.h) */
int getch2(int time)
{
	int i,term,timeout,status;

	timeout = (time+500000)/1000000;
	status = smg$read_keystroke(&kid, &term, 0, &timeout, 0, 0, 0);
	if ((status == SS$_TIMEOUT) | !(status & 1))return -1;
	for (i=0; getch2_keys[i].trm; i++) {
		if (getch2_keys[i].trm == term) return getch2_keys[i].code;
	}
	return (term & 0xff);
}
