\ 1802memory

needs double
needs mem

decimal

create memfallback   256 allot

2variable mem   0. mem 2!
variable addrmax    0 addrmax !

: c!mem  ( byte 1802addr -- )
    0   mem 2@ d+  c!a ;   inline

: c@mem  ( 1802addr -- byte )
    0    mem 2@ d+ c@a ;    inline

\ Fetch a byte from the virtual 1802
\ memory space.
: byte@  ( 1802addr -- byte )
    addrmax @ and   c@mem ;

variable memprotect
0 memprotect !

: set-memprotect  ( flag -- )
    memprotect ! ;

: memprotect?  ( -- flag )
    memprotect @ ;  inline

: byte!  ( byte 1802addr -- )
    memprotect? if
        2drop
    else
        addrmax @ and  c!mem
    then ;

: free-mem  ( -- ) 
    mem 2@  or if
        mem 2@ (free) drop 
        0. mem 2!
    then ;

: (allocate-mem)  ( -- )
    mem 2@ or 0= if
        16384 (allocate) throw
        mem 2!
    then ;

: allocate-mem  ( -- )
    ['] (allocate-mem) catch if
        memfallback >abs mem 2!
    then ;

: fallback?  ( -- flag )
    mem 2@   memfallback >abs  d= ;

: set-mem-256  ( -- )
    allocate-mem
    255 addrmax ! ;

: set-mem-4k  ( -- )
    allocate-mem
    4095 addrmax !
    fallback? if
        5070 FrmAlert drop
        set-mem-256
    then ;

: set-mem-16k  ( -- )
    allocate-mem
    16383 addrmax !
    fallback? if
        5070 FrmAlert drop
        set-mem-256
    then ;



