/*
 *	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 "variable.h"
#include "state.h"
#include "portme.h"
#include "messages.h"
#include "story.h"
#include "memory.h"


uint32_t variableAddressGlobal(uint16_t var) {
	return storyGlobalVariableTableAddress() + ((var - 16) * 2);
}


uint16_t variableLoad(uint16_t var) {
	// Is it on the stack?
	if (var <= 16) return __state.stack[variableAddress(var, false)];
	// Nope, global.
	return ZPEEKW(variableAddressGlobal(var));
}


void variableStore(uint16_t var, uint16_t value) {
	if (var <= 16) {
		// On stack.
		__state.stack[variableAddress(var, true)] = value;
	} else {
		// Global.
		ZPOKEW(variableAddressGlobal(var), value);
	}
}


uint8_t variableAddress(uint8_t var, bool writing) {
	uint16_t numLocals;

	// Top of stack.
	if (var == 0) {
		if (writing) {

			if (__state.sp >= sizeof(__state.stack)) portDie(MSG_INT_STACK_OVERFLOW);
#ifdef DEBUGGINGx
			printf("Push stack\n");
#endif
			return __state.sp++;

		} else {

			if (__state.sp == 0) portDie(MSG_INT_STACK_UNDERFLOW);
			numLocals = __state.bp ? __state.stack[__state.bp - 1] : 0;
			if ((__state.bp + numLocals) >= sizeof(__state.stack)) portDie(MSG_INT_STACK_UNDERFLOW);
#ifdef DEBUGGINGx
			printf("Pop stack\n");
#endif
			return --__state.sp;

		}  // writing
	}  // var

	// Local var.
	if ((var >= 0x1) && (var <= 0xf)) {
		if (__state.stack[__state.bp - 1] <= (var - 1)) portDie(MSG_INT_REF_UNALLOCATED_LOCAL);
		return __state.bp + (var - 1);
	}

	return variableAddressGlobal(var);
}
