#include <intuition/intuition.h>

#define LF 0x0A
#define CR 0x0D
#define BS 0x08
#define DEL 0x7f
#define CSI 0x9b
#define ESC 0x1b

#define DELCHAR "\033[P"

void handle_console_read(struct MsgPort *, char *);
void handle_window(struct Window *, int *);
int send_to_host(struct MsgPort *, char *, int);

extern struct IOStdReq	*writeReq;
extern struct MsgPort *wait_port;
extern int local_echo;

char sendbuf[200];  /* collect the line we are typing in this array */
char pos = 0;

void handle_console_read(struct MsgPort *readport, char *inputbuffer)
{
    unsigned char ch;	/* the char read */
    char obuf[80];	/* string to write on console */
    static int in_control = 0;

    if((ch = ConMayGetChar(readport, inputbuffer)) != -1) {

	/* handle escape sequences */
	if(in_control == 1) {
	    if(ch =='[')
		in_control = 2;
	    else
		in_control = -2;
	}

	if((ch == CSI) || (ch == ESC)) /* control sequence start */
	    in_control = (ch == ESC) ? 1 : 2;

	if(!in_control) {
	    if(ch == CR) {
		sprintf(obuf,"%c%c", LF, CR);   /* move cursor to next line */
		ConPuts(writeReq,obuf);
		sendbuf[pos] = LF;
		pos++;
		send_to_host( wait_port, sendbuf, pos);
		pos = 0;
		}
	    else if(ch == BS) {
		if(pos > 0) {
		    pos--;
		    sprintf(obuf,"%c%s", BS, DELCHAR);
		    ConPuts(writeReq,obuf);
		    }
		}
	    else if(( (ch >= 0x1f) && (ch <= 0x7e) || (ch >= 0xa0) )) {
		sprintf(obuf,"%c", ch);
		if(local_echo)
		    ConPuts(writeReq,obuf);
		sendbuf[pos] = obuf[0];
		pos++;
		}
	}

	if((in_control == 3) && ((ch >= 0x40) && (ch <= 0x7e)))
	    in_control = -1;

	if(in_control == 2)
	    in_control = 3;    /* we are inside a escape sequence */

	if(in_control < 0)
	    in_control = 0;    /* ESC sequence ended */
    }
}


void handle_window(struct Window *win, int *abort)
{
    struct IntuiMessage *winmsg;

    while(winmsg = (struct IntuiMessage *)GetMsg(win->UserPort)) {
	switch(winmsg->Class) {
	    case CLOSEWINDOW:
		*abort = TRUE;
		break;
	    default:
		break;
	    } /* end switch */
	ReplyMsg((struct Message *)winmsg);
	}
}
