include "inc/cmdsys.plh"
//
// Wait for VBL
//
export asm waitVBL#1
!SOURCE    "vmsrc/plvmzp.inc"
        LDA     #$00
        STA     TMPH
        STA     TMPL
        PHP             ; //c version first because its largest
        SEI
        STA     $C07F   ; Enable IOU access and reset VBL int on //c
        LDA     $C041   ; Save VBL int state MSB = BVL int enebaled
        STA     $C05B   ; Enable VBL int
        STA     $C070   ; Reset VBL int on //c
-       INC     TMPL
        BNE     +
        INC     TMPH
+       BIT     $C019
        BPL     -       ; Wait for VBL
        ASL
        BCS     +
        STA     $C05A   ; Disable VBL int on //c
+       STA     $C07E   ; Disable IOU access on //c
        PLP
        DEX
        LDA     TMPL    ; Return count
        STA     ESTKL,X
        LDA     TMPH
        STA     ESTKH,X
        RTS
end
asm _vbl2e#1
        LDA     #$00
        STA     TMPH
        STA     TMPL
-       LDA     $C019   ; //e version
        BPL     -
-       INC     TMPL
        BNE     +
        INC     TMPH
+       LDA     $C019   ; Wait during active video
        BMI     -
        DEX
        LDA     TMPL    ; Return count
        STA     ESTKL,X
        LDA     TMPH
        STA     ESTKH,X
        RTS
end
asm _vblnop#1
        LDA     #$00    ; NOP version
        DEX             ; return FALSE
        STA     ESTKL,X
        STA     ESTKH,X
        RTS
end
asm _vblend#1
end
def _vbl3
    byte params[6]
    char syn

    syn      = 22
    params.0 = 3
    params.1 = cmdsys.refcons
    params:2 = @syn
    params:4 = 1
    syscall($CB, @params)
    return 300
end
//
// Check for machine specific VLB handling
//
when MACHID & MACHID_MODEL
    is MACHID_IIE
        memcpy(@waitVBL, @_vbl2e, @_vblnop-@_vbl2e)
    is  MACHID_IIC
        break
    is MACHID_III
        waitVBL.0 = $4C // JMP
        waitVBL:1 = @_vbl3
        break
    otherwise
        memcpy(@waitVBL, @_vblnop, @_vblend-@_vblnop)
wend
//
// Keep module in memory
//
return modkeep
done
