; (C): copyright 2022 Peter Ped Helcmanovsky, license: MIT
; name: Test if the CPU does use 0x30 vector when IM1 interrupt hits during JR, instead of 0x38
; this is behaviour of web simulator: visual Z80 remix
; (it's very unlikely you would use such CPU with real ZX Spectrum, as it would be quite unstable in BASIC)
;
; to assemble (with z00m's sjasmplus https://github.com/z00m128/sjasmplus/ v1.18.3+)
; run: sjasmplus z80_im1_vs_jr.asm

    OPT --syntax=abf
    DEVICE zxspectrum48, $7FFF
    ORG $8000
code_start:
    ; comes from BASIC, EI=on, IM1
    ld hl,jr_block
    ld de,jr_block+2
    ld bc,$7e00 ; about 390k T to catch few interrupts even on turbo machines
    ldir ; create block of many `jr $+2` (opcode: 18 00)
    halt ; sync to BASIC IM1 to have it happen later, then do remaining setup
    ; append `jp test_end` after the block
    ld de,test_end
    ld (hl),$C3
    inc hl
    ld (hl),e
    inc hl
    ld (hl),d
    ; setup registers for the test
    ld bc,2 ; in case rst 0x30 handles IM1, allocate BC_SPACES of size 2 (safe to do several times)
    ld h,b
    ld l,b ; hl = 0 (to see if rst 0x30 or rst 0x38 handler was used for IM1)
    jr jr_block ; start the long JR block, waiting for few interrupts
test_end:
    ld b,h
    ld c,l ; bc = hl as result
    ret
jr_block:
    jr $+2
code_end:

tkCODE      EQU     $AF
tkUSR       EQU     $C0
tkLOAD      EQU     $EF
tkCLEAR     EQU     $FD
tkRANDOMIZE EQU     $F9
tkREM       EQU     $EA
tkIF        EQU     $FA
tkTHEN      EQU     $CB
tkPRINT     EQU     $F5
tkSTOP      EQU     $E2

    ;; produce TAP file with the test code
        DEFINE tape_file "z80im1jr.tap"
        DEFINE prog_name "im1 vs jr"

        ;; 10 CLEAR 32767:LOAD "im1 vs jr"CODE
        ;; 20 IF USR 32768 THEN PRINT "IM1 landed to 0x30": STOP
        ;; 30 PRINT "IM1 operating normally"
        ORG     $5C00
tap_bas:
        DB      0,10    ;; Line number 10
        DW      .l10ln  ;; Line length
.l10:   DB      tkCLEAR,"32767",$0E,0,0
        DW      code_start-1
        DB      0,':'
        DB      tkLOAD,'"'
.fname: DB      prog_name
        ASSERT  ($ - .fname) <= 10
        DB      '"',tkCODE,$0D
.l10ln: EQU     $-.l10
        DB      0,20    ;; Line number 20
        DW      .l20ln
.l20:   DB      tkIF,tkUSR,"32768",$0E,0,0
        DW      code_start
        DB      0
        DB      tkTHEN,tkPRINT,"\"IM1 landed to 0x30\":",tkSTOP,$0D
.l20ln: EQU     $-.l20

        DB      0,30    ;; Line number 30
        DW      .l30ln
.l30:   DB      tkPRINT,"\"IM1 operating normally\"",$0D
.l30ln: EQU     $-.l30
;         DB      0,99    ;; Line number 99
;         DW      .l99ln
; .l99:   DB      tkREM,"https://github.com/MrKWatkins/ZXSpectrumNextTests/\r"
; .l99ln: EQU     $-.l99
.l:     EQU     $-tap_bas

        EMPTYTAP tape_file
        SAVETAP  tape_file,BASIC,prog_name,tap_bas,tap_bas.l,1
        SAVETAP  tape_file,CODE,prog_name,code_start,code_end-code_start,code_start
