#include	<curses.h>

#define	printf	print

static char	kbd_mess[2] = {
			DISABLE_MOUSE,
			SET_REL_MOUSE
		};

static int	save_pallette[16];

init_curses()
{

int	i;
int	pallette[16];

	for (i=0; i<16; i++) save_pallette[i] = Setcolor(i, -1);
	for (i=0; i<16; i++) pallette[i] = 0xffff;
	pallette[0] = 0;
	Setpallete(pallette);
	Vsync();
	Ikbdws(0, kbd_mess);
	scr_func(HIDE_CURS);
	scr_func(CLEAR_SCR);
	Cursconf(2, 0);
	scr_func(SHOW_CURS);
}

curses_cleanup()
{
	scr_func(HIDE_CURS);
	Ikbdws(0, kbd_mess+1);
	if (Getrez() < 2)
		Setpallete(save_pallette);
}

pos_cursor(x, y)
int	x, y;
{
	char out;

	scr_func(POS_CURS);
	out = y + 32;
	char_out(out);
	out = x + 32;
	char_out(out);
}

scr_func(func)
char	func;
{
	char_out(27);
	char_out(func);
}

char_out(chrout)
char	chrout;
{
	while(!Cconos());
	Cconout(chrout);
}

int get_str(string)
unsigned char	*string;
{
	unsigned char	key, *str_pos;

	str_pos = string;
	do {
		key = Crawcin();
		if (key < 32 || key == 127) 
			switch ((int) key) {
			case ESCAPE:
				*str_pos = '\0';
				return(-1);
				break;
			case BACKSPACE:
			case DELETE:
				if (str_pos > string) {
					erase_char();
					str_pos--;
				} else {
				char_out(BELL);
				}
				break;
			case CARRIAGE_RETURN:
				*str_pos = '\0';
				return((int)((long)str_pos - (long)string));
				break;
			case DEL_WORD:
				do {
					if (str_pos == string) char_out(BELL);
					else {
						erase_char();
						str_pos--;
						if (*(str_pos-1) == ' ') break;
					}
				} while (str_pos > string);
				break;
			case DEL_LINE:
			case CANCEL:
				if (str_pos == string) char_out(BELL);
				else while (str_pos > string) {
					erase_char();
					str_pos--;
				}
				break;
			default:
				char_out(BELL);
				break;
			}
		else {
			char_out(key);
			*str_pos++ = key;
		}
	} while (TRUE);
}

erase_char()
{
	scr_func(BACK_CURS);
	char_out(' ');
	scr_func(BACK_CURS);
}

stderr(message)
char	*message;
{
	scr_func(CLEAR_SCR);
	printf("%s\n\r", message);
	printf("... Hit any key to exit\n\r");
	wait();
	curses_cleanup();
	exit(-1);
}
