#include <fishtalk.h>

void ft_cmd_queue(FT_HANDLE handle, const char* buffer) {
	int i;

	for(i = 0; buffer[i] != 0; i++) {
		if(buffer[i] == '\n' || buffer[i] == ']') {
			int  j;
			long old;

			if(handle->buffer_size > 0) {
				old = 0;
				for(j = 0; j <= handle->buffer_size; j++) {
					if(j == handle->buffer_size) {
						char* buf = &handle->buffer[old];
						int   len, sj;

						for(sj = j; sj >= old; sj--) {
							if(!FT_IS_SKIPPABLE(handle->buffer[sj])) break;
						}

						len = sj - old;

						ft_phon_main(handle, buf, len);

						old = j;
					}
				}
			}

			if(handle->cmd_buffer_size > 0) {
				old = 0;
				for(j = 0; j <= handle->cmd_buffer_size; j++) {
					if(j == handle->cmd_buffer_size) {
						char* buf = &handle->cmd_buffer[old];
						int   len, sj;

						for(sj = j; sj >= old; sj--) {
							if(!FT_IS_SKIPPABLE(handle->cmd_buffer[sj])) break;
						}

						len = sj - old;

						ft_cmd_main(handle, buf, len);

						old = j;
					}
				}
			}

			handle->buffer_size	= 0;
			handle->cmd_buffer_size = 0;
			handle->in_cmd		= 0;
		} else {
			if(buffer[i] == '[') {
				handle->in_cmd = 1;
			} else if(handle->in_cmd) {
				if(handle->cmd_buffer_size == 0 && FT_IS_SKIPPABLE(buffer[i])) continue;

				handle->cmd_buffer[handle->cmd_buffer_size++] = buffer[i];
			} else {
				if(handle->buffer_size == 0 && FT_IS_SKIPPABLE(buffer[i])) continue;

				handle->buffer[handle->buffer_size++] = buffer[i];
			}
		}
	}
}

void ft_cmd_main(FT_HANDLE handle, const char* buffer, long length) {
	/* TODO */
	fprintf(stderr, "cmd: ");
	fwrite(buffer, length, 1, stderr);
	fprintf(stderr, "\n");
}
