/* v03.c
 * Visual Editor, Speicherverwaltung testen
 * Autor: Andre Adrian
 * Version: 01Feb2011 fuer CP/M, MS-DOS, MS-Windows, Linux
 */
 
#include <stdio.h>
#include <stdlib.h>
#ifdef CPM
#	include <conio.h>
#	define system(s)
#endif
#if defined(_MSC_VER) || defined(__TURBOC__)
#	include <conio.h>
#	define putch(c) putchar(c)
#	define cputs(s) fputs(s,stdout)
#	define system(s)
#endif
#ifdef linux
#	define putch(c) putchar(c)
#	define cputs(s) fputs(s,stdout)
#	define getch()  getchar()
#endif

/* Cursortasten von Tastatur */
#define ETX	('C'-'@')	/* Strg-C */
#define CUUin	('W'-'@')
#define CUDin	('X'-'@')
#define CUFin	('D'-'@')
#define CUBin	('A'-'@')

/* ANSI Escape Sequenzen an Terminal(-Emulator) */
#define CUUout	"\033[A"
#define CUDout	"\033[B"
#define CUFout	"\033[C"
#define CUBout	"\033[D"

char *text;		/* enthaelt Editortext */
unsigned int tsize;	/* Laenge von text */

int main() {
	int c;
	for (tsize = 64512; tsize >= 2048; tsize -= 1024) {
		text = (char *)malloc(tsize);
		if (text != NULL) break;
	}
	if (NULL == text) exit(1);
	text[0] = 0;	/* Textspeicher initialisieren */
	printf("text memory is %u bytes\n", tsize);

	system("stty -icanon -echo");
	do {
		c = getch();
		switch (c) {
		case CUUin:
			cputs(CUUout);
			break;
		case CUDin:
			cputs(CUDout);
			break;
		case CUFin:
			cputs(CUFout);
			break;
		case CUBin:
			cputs(CUBout);
			break;
		default:
			if (c >= 32 && c <= 126) {
				putch(c);
			} else {
				printf("<%02x>", c);
			}
			break;
		}
	} while (c != ETX);
	system("stty sane");
	return 0;
}