;*******************************************************************
;       Procedure Name  : read_joypad
;
;       Author          : ?? Accepted code, commented by Marc Gale
;
;       Description     : Read the joypad and return the value in A.
;                       : The values returned are:
;
;                               $8 - Start      $80 - Down
;                               $4 - Select     $40 - Up
;                               $2 - Button B   $20 - Left
;                               $1 - Button A   $10 - Right
;
;       On Entry        : Nothing required
;
;       During          : A is modified
;                       : B is used as a temporal store
;
;       On Exit         : Nothing intentional
;*******************************************************************
read_joypad
 ld     a,$20                   ; Bit 5 = $20
 ld     [$ff00],a               ; Select P14 by setting it low
 ld     a,[$ff00]
 ld     a,[$ff00]               ; Wait a few cycles
 cpl                            ; Complement A [invert it]
 and    $0f                     ; Mask so that we only get the right
				; hand four BITs
 swap   a                       ; Move the right hand four BITs to 
				; the left hand four BITs
 ld     b,a                     ; Store A in B
 ld     a,$10                   ; Bit 4 = $10
 ld     [$ff00],a               ; Select P15 by setting it low
 ld     a,[$ff00]
 ld     a,[$ff00]
 ld     a,[$ff00]
 ld     a,[$ff00]
 ld     a,[$ff00]
 ld     a,[$ff00]               ; Wait a few MORE cycles
 cpl                            ; Complement A [invert it]
 and    $0f                     ; Mask so that we only get the right
				; hand four BITs
 or     b                       ; Meld A and B together
 ld     b,a                     ; Store A in B
 ld     a,$30                   ; Bit 4 AND 5 = $30
 ld     [$ff00],a               ; Deselect P14 and P15
 ld     a,b                     ; Put the joypad result in A
 ret                            ; Return from the procedure