; Purpose: This routine checks all of Extended RAM to ensure 
;          it is working correctly.  Extended RAM is in the 
;          address range of $4000-$7FFF, and uses banks 0-31.  
;          This method does NOT maintain state of registers 
;          coming in because it expects to be run on its own
;          or in a series of equally self contained tests.
; For: NerdConsole (65C02 Assembly, ca65 format)
; By: David Stephens (NerdOfEpic)
; License: Public Domain - Can be used or modified by anyone 
;                          for any purpose.


; Control Page Registers
ExtendedRamBank     = $020D

; Constants
LastBank            = $1F ; The last bank to test (counts down to 0).
TestPatternCount    = $06 ; The number of patterns to test.
RegionPageStart     = $40 ; The starting page in the memory region.
RegionPageCount     = $40 ; The number of pages in the memory region.

; Location of state and results
; Result of: $00 = Pass / non-$00 = Fail
; Some tests have multiple failure reasons.
ResultValue         = $80 ; Where the result for this test is stored.
CurrentPattern      = $D0 ; Which test pattern is currently being used.
CurrentBank         = $D1 ; The current bank being tested.
CurrentPage         = $D2 ; Set $D3 (not $D2!) to the current page

; Bit patterns for the RAM tests that will be performed.  Each 
; pattern is a single byte.
TestPatterns:
.byte $FF, $00, $55, $AA, $33, $CC 


RamCheckExtended:
    ; Setup
    lda #$00               ; Assume we will succeed
    sta ResultValue
    
    lda #LastBank          ; Checks 32 banks (tests them backwards).
    sta ExtendedRamBank    ; Control Page - Set bank.
    sta CurrentBank        ; Save the current
    
    stz CurrentPage        ; Start checking at $4000 
    lda #RegionPageStart
    sta CurrentPage+1   
    
    stz CurrentPattern     ; Start with the first one
    ldy CurrentPattern
    lda (TestPatterns),y
    
    ; Test the current bank/page/pattern
BankLoop:    

PageLoop:

PatternLoop:
    
RamFillLoop:
    ldx #$00
    sta (CurrentPage),x   ; acc has current pattern
    inx
    bne RamFillLoop 
    
    sta #$00 ; Prep for test

RamTestLoop:    
    ldx #$00
    ora (CurrentPage),x
    inx
    bne RamTestLoop 
    
    ; Make sure we got the value we expected
    ldy CurrentPattern
    cmp (TestPatterns),y
    bne RamCheckExtendedFailed
    
    ; Prepare for the next page
    


RamCheckExtendedFailed:
    lda #$01
    sta ResultValue
    bra RamCheckExtendedDone

RamCheckExtendedDone: