;
;	ZX Diagnostics - fixing ZX Spectrums in the 21st Century
;	https://github.com/brendanalford/zx-diagnostics
;
;	Original code by Dylan Smith
;	Modifications and 128K support by Brendan Alford
;
;	This code is free software; you can redistribute it and/or
;	modify it under the terms of the GNU Lesser General Public
;	License as published by the Free Software Foundation;
;	version 2.1 of the License.
;
;	This code is distributed in the hope that it will be useful,
;	but WITHOUT ANY WARRANTY; without even the implied warranty of
;	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;	Lesser General Public License for more details.
;
;	testram.asm
;	

;
;	Launcher for Spectrum Diagnostics Test Program
;
;	Performs a checksum on testrammain.bin, and launches
;	only if the checksum is as expected.
;
;	Checksum is generated by LUA scripting.
;

;	Modify this value in tandem with the value of label start in testrommain.asm

	define start_diags		0x0100

	LUA ALLPASS

	file = io.open("testrommain.bin", "rb")
	io.input(file)
	chk = 0
	size = 0
	local data = io.read(1)
	
	while size < (0x3fbf - 0x38) do
	    chk = (chk + string.byte(data)) % 0x10000
	    data = io.read(1)
		size = size + 1
	end
	io.close(file)
	sj.insert_define("TESTROM_CHECKSUM", chk);

	ENDLUA

	org 0
	
	di 
	ld ix, 56
	ld hl, 0
	ld d, 0

;
;	Compute 16 bit addition checksum on code from
;	56 (0x38) to 16319 (0x3FBF) - ignore last 64 bytes for 
;	ZXC3/ZXC4 compatibility
;

checksum
	
	ld a, (ix)
	ld e, a
	add hl, de
	inc ix
	ld a, ixh
	cp 0x3f
	jr nz, checksum
	ld a, ixl
	cp 0xbf
	jr nz, checksum

	ld de, TESTROM_CHECKSUM

	ld a, d
	cp h
	jr nz, error
	ld a, e
	cp l
	jr nz, error
	jp start_diags
	
error

	inc a
	out (0xfe), a
	jr error
	
	BLOCK $38-$, #FF
	
test_rom

	incbin "testrommain.bin"
