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


void storyChecksumCalculate(void) {
	uint32_t i;

	__state.checksum = 0;
	for (i=64; i<storyLength(); i++) __state.checksum += ZPEEK(i);

	__state.checksum %= 0x10000;

#ifdef DEBUGGING
	printf("\n\nChecksum = %u   Header = %d\n\n", __state.checksum, storyChecksum());
#endif
}


uint32_t storyLength() {
	uint32_t m = (uint32_t)storyFileSize() * 2;

	if (storyVersion() >= 4) m *= 2;
	if (storyVersion() >= 6) m *= 2;

	if (m == 0) {
		// Some old stories do not have the size in the header.
		//***TODO***
	}

	return m;
}


void storySetup(byte width, byte height) {
	char     *p;
	uint16_t  i;

	// Set display size.
	ZPOKE(STORY_SCREEN_WIDTH_CHARACTERS, width);
	ZPOKE(STORY_SCREEN_HEIGHT_LINES, height);

	// Enable status bar.
	ZPOKE(STORY_FLAG_V3, ZPEEK(STORY_FLAG_V3) & ~STORY_FLAG_V3_STATUS_LINE_NOT_AVAILABLE);
	ZPOKE(STORY_FLAG_V3, ZPEEK(STORY_FLAG_V3) | STORY_FLAG_V3_SCREEN_SPLITTING);

	// V6+ this is the address of main(), not just a raw starting address.
	__state.pc = storyInitialPC();
	__state.sp = 0;

	// Set up alphabet tables.  ***TODO*** V5+ has alternate tables in header.
	p = __state.alphabetTable;
	for (i=0; i<26; i++) *(p++) = 'a' + i;  // Alphabet A0
	for (i=0; i<26; i++) *(p++) = 'A' + i;  // Alphabet A1
	// Alphabet A2
	*(p++) = 0;
	if (storyVersion() != 1) *(p++) = '\n';
	for (i=0; i<10; i++) *(p++) = '0' + i;
	*(p++) = '.';
	*(p++) = ',';
	*(p++) = '!';
	*(p++) = '?';
	*(p++) = '_';
	*(p++) = '#';
	*(p++) = '\'';
	*(p++) = '"';
	*(p++) = '/';
	*(p++) = '\\';
	if (storyVersion() == 1) *(p++) = '<';
	*(p++) = '-';
	*(p++) = ':';
	*(p++) = '(';
	*(p++) = ')';
}
