     .OUTPI ALFRES
     .ENTRY MALLOC,MINIT

;This routine allocates memory from the system area.
;On entry, if Acc=0 then X/Y is the size of buffer to allocate.
;If Acc is non-zero then the request is for all the memory.

;On Exit, cc if request satisfied, XY is address of the buffer start.
;For malloc all, len has the length of the buffer returned

MBOT .WORD 0
MSIZE .WORD 0

MINIT  LDA $02E7
       STA MBOT     GET RAM SIZE
       LDA $02E8
       STA MBOT+1
       LDA #.LO.DZTOP
       SEC
       SBC $02E7
       STA MSIZE
       LDA #.HI.DZTOP
       SBC $02E8
       STA MSIZE+1
       RTS

MALLOC CMP #0      WANTS IT ALL ?
       BEQ MAL010  BR IF NO
       LDX MBOT
       LDY MBOT+1
       LDA MSIZE
       STA LEN
       LDA MSIZE+1
       STA LEN+1
       CLC
       RTS
MAL010 CPY MSIZE+1   CHECK FOR SIZE
       BCC MAL012    IS LESS
       BEQ MAL011
       RTS           IS TOO BIG
MAL011 CPX MSIZE
       BCC MAL012
       BEQ MAL012
       RTS           IS TOO BIG
MAL012 STX $FE
       STY $FF
       LDX MBOT
       LDY MBOT+1    BUFFER ADDRESS
       LDA MBOT
       CLC
       ADC $FE
       STA MBOT
       LDA MBOT+1
       ADC $FF
       STA MBOT+1
       LDA MSIZE
       SEC
       SBC $FE
       STA MSIZE
       LDA MSIZE+1
       SBC $FF
       STA MSIZE+1
       CLC
       RTS
