#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include "zfifo.h"


mawk_state_t *MAWK = NULL;
int main(int argc, char *argv[])
{
	mawk_zfifo_t fifo;

	while(!(feof(stdin))) {
		char line[1024], *cmd, *args;
		*line = '\0';
		fgets(line, sizeof(line), stdin);

		cmd = line;
		while(isspace(*cmd)) cmd++;
		if ((*cmd == '#') || (*cmd == '\0'))
			continue;
		args = strpbrk(cmd, " \t\r\n");
		if (args != NULL) {
			*args = '\0';
			args++;
		}

		if (strcmp(cmd, "alloc") == 0) {
			mawk_zfifo_alloc(MAWK, &fifo, (args == NULL ? -1 : atoi(args)));
			printf(">alloc: %d\n", fifo.max_size);
		}
		else if (strcmp(cmd, "free") == 0) {
			mawk_zfifo_free(MAWK, &fifo);
			printf(">free\n");
		}
		else if (strcmp(cmd, "write") == 0) {
			int len;
			assert(args != NULL);
			len = strlen(args)-1;
			while((len > 0) && ((args[len] == '\n') || (args[len] == '\r'))) {
				args[len] = '\0';
				len--;
			}
			len++;
			printf(">write: %d '%s'\n", mawk_zfifo_write(MAWK, &fifo, args, len), args);
		}
		else if (strcmp(cmd, "read") == 0) {
			int size = sizeof(line)-1;
			int ret;
			if (args != NULL)
				size = atoi(args);
			*line = '\0';
			ret = mawk_zfifo_read(MAWK, &fifo, line, size);
			if (ret >= 0)
				line[ret] = '\0';
			else
				line[0] = '\0';
			printf(">read: %d '%s'\n", ret, line);
		}
		else if (strcmp(cmd, "dump") == 0) {
			mawk_zfifo_block_t *b;
			printf(">dump\n");
			printf(" Size: %d/%d\n", fifo.size, fifo.max_size);
			for(b = fifo.head; b != NULL; b = b->next) {
				int n;
				memcpy(line, b->buf, b->size);
				line[b->size] = '\0';
				printf("  blk %03d from %03d '%s'\n", b->size, b->readp, line);
				printf("                    ");
				for(n = b->readp; n > 0; n--)
					printf(" ");
				printf("^--readp\n");
			}
			if (fifo.stage_used > 0)
				memcpy(line, fifo.stage_buf, fifo.stage_used);
			line[fifo.stage_used] = '\0';
			printf("  stg %d '%s'\n", fifo.stage_used, line);
		}
		else if (strcmp(cmd, "exit") == 0) {
			break;
		}
		else {
			fprintf(stderr, "Syntax error at invalid command '%s'\n", cmd);
		}
	}

	return 0;
}
