;=================================================================
; [OHJOY.INC] -- Joypad detection and handling routines
;=================================================================


.ENUM $20                       ; $20-$27
    joy1 DW                     ; Current button state for pad 1&2. Bit #0
    joy2 DW                     ; .. = 0 if joypad is valid.
    joy1press DW
    joy2press DW
.ENDE


.DEFINE HVBJOY	$4212
.DEFINE JOY0	$4218
.DEFINE JOY1	$421A
.DEFINE JOY2	$421C
.DEFINE JOY3	$421E
.DEFINE JOYSER0	$4016
.DEFINE JOYSER1	$4017
.DEFINE WRIO	$4201


;=================================================================


.BANK 0
.ORG HEADER_OFF
.SECTION "initjoycode" SEMIFREE

INIT_JOY:
    php
    rep   #$10                  ; A/mem=8bits, X/Y=16bits
    sep   #$20
    lda   #$C0                  ; Automatic read of the  first pair two pads
    sta   WRIO
    ldx   #$0000
    stx   joy1press
    stx   joy2press
    lda   #$81
    sta   $4200                 ; Enable joypad-read and NMI
    wai
    plp
    rts
.ENDS


;=================================================================


.BANK 0
.ORG HEADER_OFF
.SECTION "JoyInput" SEMIFREE

JOY_GETINPUT:
    php
    sep   #$20                  ; A/mem=8bits
    lda   #$01
_JGI_W1:
    bit   $4212
    bne   _JGI_W1
    rep   #$30                  ; A/mem=X/Y=16bits
    lda   JOY0
    tax
    eor   joy1
    stx   joy1
    ora   joy1press
    and   joy1
    sta   joy1press
    lda   JOY1
    tax
    eor   joy2
    stx   joy2
    ora   joy2press
    and   joy2
    sta   joy2press

    ; Are the pads valid?
    sep   #$30                  ; A/mem=X/Y=8bits
    lda   JOYSER0
    eor   #$01
    and   #$01
    ora   joy1
    sta   joy1
    lda   JOYSER1
    eor   #$01
    and   #$01
    ora   joy2
    sta   joy2

    ; Change any invalid pad to have a state of "no-buttons-pressed"...
    rep   #$30                  ; A/mem=X/Y=16bits
    ldx   #$0001
    lda   #$000F
    bit   joy1
    beq   _JGI_J2
    stx   joy1
    stz   joy1press
_JGI_J2:
    bit   joy2
    beq   _DONE
    stx   joy2
    stz   joy2press
_DONE:
    plp
    rtl

.ENDS
