P*      
* El Cheapo Assembler
*
* Utility routines -- init, memory management
*

         DSK '@0:init'
         REL

ASSEMBLE EXT
EDITOR   EXT
TEXTEND  EXT
CODEEND  EXT
DORG     EXT
BLSTART  EXT
BLEND    EXT
BLDEST   EXT
BLMOVE   EXT

         JMP INIT
         JMP ASSEMBLE
         JMP EDITOR

INIT     
         LDA #$4C         ;JMP -- use SYS 822 to re-enter
         STA $0336
         LDA #<RESTORE
         STA $0337
         LDA #>RESTORE
         STA $0338
         LDA #$0D
         STA $0800        ;Text starts at $0800
         LDA #00
         STA $0801
INIT2    
         LDA #$36         ;No BASIC
         STA $01
         STA CODEFLAG     ;No code present
         JMP EDITOR

*
* Current scheme:
*   $0334-$0338   Vectors
*   $0800-$xxxx   Source code
*   $8xxx-$9xxx   JamaicaMon
*   $9xxx-$BFFF   El Cheapo
*   $010800-$01xxxx Compiled code
*                   Also storage for source code
*

MONITOR  ENT

         JSR FIXMEM
         JMP ($0334)      ;Off into the monitor

BASIC    ENT
         JSR FIXMEM
         LDA #$37
         STA $01
         JMP ($A002)

RESTORE                   ;Re-enter code
         JSR SWAP
         SEC
         HEX FB
         JMP INIT2

FIXMEM   
         LDA CODEFLAG
         BEQ :TEXT
         LDA TEXTEND      ;Swap code and text
         CMP CODEEND
         LDA TEXTEND+1    ;Figure out highest address
         SBC CODEEND+1    ;that needs swapping
         BCS :TEXT
         LDA CODEEND+1
         DFB $2C
:TEXT    LDA TEXTEND+1
         SEC
         SBC #$07         ;Both start at $0800
         STA XLEN+1       ;-7 to move to last page
         LDA #00
         STA XLEN

         JSR SWAP

         HEX C230         ;REP #$30 -- all 16-bits
         LDA DORG         ;Finally, move assembled code
         STA BLDEST       ;to proper location
         LDA #$00
         DFB 08           ;LDA #$0800
         STA BLSTART
         LDA CODEEND
         STA BLEND
         SEC
         HEX FB           ;XCE
         JMP BLMOVE       ;...and hope it doesn't hit us!

* Swap banks 0 and 1

SWAP     
         CLC
         HEX FB           ;XCE
         HEX C230         ;REP #$30
         HEX E220         ;SEP #$20
         LDX #00
         DFB 00           ;LDX #$0000
:LOOP    LDA $0800,X
         PHA
         HEX BF000801     ;LDA $010800,X
         STA $0800,X
         PLA
         HEX 9F000801     ;STA $010800,X
         INX
         CPX XLEN
         BNE :LOOP
         RTS

CODEFLAG ENT
         DFB 00

XLEN     DA 00            ;Number of bytes to swap
