; jumptab.asm
; by Erik Huizing
; ehuizing@ucalgary.ca

; Here's an easy way to implement
; CALL and JUMP rellocation in ZShell

; How it works
; given a table of addresses
; this algorithm will built another
; table of those addresses with
; (PROGRAM_ADDR) added to it.

; Begin relocating the entries in the jump table
; since these are in TEXT_MEM2, this doesn't
; mess around with your program's checksum
; Just put this code at the start of your program

reStart:
ld hl, jumpTab
ld bc, (PROGRAM_ADDR)
add hl, bc
ld de, TEXT_MEM2
ld a, 2 ; number of addresses to rellocate
reloc_loop:
 push hl
 push af
 CALL LD_HL_MHL
 pop af
 add hl, bc
 ex de, hl
 ld (hl), 0xC3 ; opcode for JP
 inc hl
 ld (hl), e
 inc hl
 ld (hl), d
 inc hl
 ex de, hl
 pop hl
 inc hl
 inc hl
 dec a
jr nz, reloc_loop 

routine1:
; stuff
ret

routine2:
; stuff
ret

; for the jump table, you only need to supply
; the addresses you want relocated
; the algorithm automatically puts a 
; 'jp' in front of the address
jumpTab:
.dw routine1
.dw routine2

ROUTINE1 EQU TEXT_MEM2
ROUTINE2 EQU TEXT_MEM2 + 3
; ... etc for each of your routines
; to call a routine, do this:
; CALL ROUTINE1
;
; The calc will jump to TEXT_MEM2 which
; contains the instruction jp routine1
; but routine1 has (PROGRAM_ADDR) added to it
; already.

