; c02 Program Initialization Code for Commander X16
; Compatible with x16emu Release 34

;PETSCII Key Mappings
DELKEY  EQU $14   ;Delete/Backspace Key (Delete)
ESCKEY  EQU $03   ;Escape/Stop Key      (RUN/STOP)
RTNKEY  EQU $0D   ;Return/Enter Key     (RETURN)

;       $00-$01   ;Miscellaneous Pointer
;       $02-$21   ;ABI Registers
;       $22-$52   ;Used by Basic graphics commands
XMBANK  EQU $53   ;Extended Memory Bank 
XMADDR  EQU $54   ;Ext Memory Address
SRCPTR  EQU $56   ;Source Pointer 
DSTPTR  EQU $58   ;Destination Pointer 
BLKPTR  EQU $5A   ;Block Pointer
STKPTR  EQU $5C   ;Stack Pointer
USRPTR  EQU $5E   ;User Pointer
RANDOM  EQU $62   ;Random Number Storage 
RDSEED  EQU $63   ;Random Seed 
TEMP0   EQU $64   ;Temporary Variables 
TEMP1   EQU $65   
TEMP2   EQU $66   
TEMP3   EQU $67
TMPPTR  EQU $68   ;Temporary Pointer   
SYSBFP  EQU $6A   ;Position in System Buffr
;       $6B-$6F   ;Unused
;       $70-7F    ;Free Zero-Page for Applications
;       $80-$83   ;Used by Kernal and DOS
;       $A4-$A8   ;Reserved for KERNAL/DOS/BASIC
;       $A9-$FF   ;Used by BASIC

;Other Constants
SYSBFL  EQU 128   ;System Buffer Length [Max String Length]
;Other Variables - User Storage Area
SYSBFR  EQU $0700 ;System Buffer 
;     $0781-$07F5 ;Unused
BLKBGN  EQU $07F6 ;Block Start Address
BLKEND  EQU $07F8 ;Block End Address
BLKLEN  EQU $07FA ;Block Length 
STKSAV  EQU $07FB ;Machine Stack Storage 
STKBGN  EQU $07FC ;Stack Start
STKEND  EQU $07FE ;Stack End 

;Machine Language Basic Stub - Same as Commodore 64
        ORG $0801              ;Start of Basic Program 
BASIC:  DC  $0C, $08           ;Pointer to Next Line
        DC  $00, $00           ;Line Number (0)
        DC  $9E                ;SYS 
        DC  $20                ;' '
        DC  $32, $30, $36 ,$32 ;"2062" 
        DC  $00                ;End of Line Marker
        DC  $00, $00           ;End of Basic Program

START:  TSX         ;Get Stack Pointer
        STX STKSAV  ;and Save for Exit
        SEC         ;Set Screen Mode 
        LDA #0      ;to 40x30 Text
        JSR $FF5F   ;using SCRMOD
        JMP MAIN    ;Execute Program

EXIT:   LDX STKSAV  ;Retrieve Saved Stack Pointer
        TXS         ;and Restore It
        RTS         ;Return to BASIC

;Poll Keyboard for Character
POLKEY  EQU $FFE4   ;Aliased to Kernal GETIN Routine

;Get Character from Keyboard
GETKEY  EQU POLKEY  ;Aliased to POLKEY Routine

;Wait for Character from Keyboard
GETCHR: JSR GETKEY  ;Poll Keyboard
        BEQ GETCHR  ;If No Key, Loop
        RTS

;Print Character to Console
PUTCHR  EQU $FFD2   ;Aliased to CHROUT Routine

;Delete Previous Character
DELCHR: LDA #DELKEY ;Load Delete Character
        JMP PUTCHR  ;Print and Return

;Advance Character to Next line
NEWLIN: LDA #RTNKEY ;Load Return Character
        JMP PUTCHR  ;Print and Return

        INCLUDE "prbyte.a02" ;PRBYTE and PRHEX routine
        INCLUDE "putstr.a02" ;PUTSTR routine
