/*
 *	Copyright (c) 2024 Scott Duensing, scott@kangaroopunch.com
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *	SOFTWARE.
 */


#include "oc_input.h"
#include "portme.h"
#include "state.h"
#include "memory.h"
#include "messages.h"
#include "interpreter.h"
#include "text.h"
#include "window.h"


void opcodes_read(void) {
	uint32_t     input    = __state.operands[0];
	byte         inputLen = ZPEEK(input++);
	byte         ch;
	uint32_t     i;

#ifdef DEBUGGING
	printf("Read from input stream: text-buffer=%X parse-buffer=%X\n", (unsigned int)__state.operands[0], (unsigned int)__state.operands[1]);
	printf("Max input: %u\n", inputLen);
#endif

	if (inputLen == 0) portDie(MSG_OP_INPUT_BUFFER_TOO_SMALL);

	windowUpdateStatusBar();

	// Read input from user.
	textInput(input, inputLen);

#ifdef DEBUGGING
	printf("Input: [");
	for (i=input; i<input+inputLen; i++) {
		ch = ZPEEK(i);
		if ((ch == '\n') || (ch == '\r') || (ch == 0)) break;
		printf("%c", ch);
	}
	printf("]\n");
#endif

	// Tidy up input.
	for (i=input; i<input+inputLen; i++) {
		ch = ZPEEK(i);
		if ((ch >= 'A') && (ch <= 'Z')) {
			// Make lowercase.
			ch -= 'A' - 'a';
			ZPOKE(i, ch);
		} else if ((ch == '\n') || (ch == '\r') || (ch == 0)) {
			// End of line, end of input.
			ZPOKE(i, 0);
			break;
		}
	}
	i++;
	for (; i<input+inputLen; i++) ZPOKE(i, 0);

	// Reset [MORE] counter.
	__state.linesOut = 0;

	interpreterTokenizeInput();
}
