; c02 Program Initialization Code for Commodore Plus/4 & 16

;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)

;Zero Page Locations
STRLO   EQU $FE   ;String Pointer (stdio.asm)
STRHI   EQU $FF   ;

;Other RAM Locations
TBFFR   EQU $0333 ;Cassette I/O Buffer

;Video RAM and ROM 
VIDSCN  EQU $0C00 ;Video Screen Memory Area 
CHRROM  EQU $D000 ;Character Generator ROM
VIDCLR  EQU $0800 ;Color RAM 

;Kernal Routines
CHROUT  EQU $FFD2 ;Output Character to Channel
GETIN   EQU $FFE4 ;Read Character from Keyboard Buffer
CHRIN   EQU $FFCF ;Input Character to Channel

;Machine Language Basic Stub
        ORG $1001              ;Start 
BASIC:  DC  $0C, $10           ; Pointer to Next Line (4108)
        DC  $00, $00           ; Line Number (0)
        DC  $9E                ; SYS 
        DC  $20                ; ' '
        DC  $34, $31, $31 ,$30 ; "4110" 
        DC  $00                ;End of Line Marker
        DC  $00, $00           ;End of Basic Program

START:  TSX         ;Get Stack Pointer
        STX user15  ;and Save for Exit
        JMP main    ;Execute Program

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

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

;Get Character from Keyboard
GETKEY  EQU POLKEY 

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

;Advance Character to Next line
NEWLIN: LDA #$0D     ;Load C/R into Accumulator
        JMP PUTCHR
        
;Print Character to Console
PUTCHR  EQU $FFD2    ;Alias to Kernal Routine CHROUT

;Delete Previous Character
DELCJR: LDA #$9D     ;Load Cursor Left into Accumulator
        JSR PUTCHR   ;  and Print it
        LDA #$14     ;Load Delete into Accumulater
        JMP PUTCHR   ;  and Print it

;Advance Character to Next line
NEWLIN: LDA #$0D     ;Load C/R into Accumulator
        JMP PUTCHR   ;  and Print it

;Print Byte as Two-Digit Hex Number to Console
PRBYTE: PHA         ;Save Accumulater
        LSR         ;Shift Hi Nybble to Low Nybble
        LSR 
        LSR 
        LSR 
        JSR prhex   ;  and Print it
        PLA         ;Restore Accumulator 
                    ;  and fall into prhex
                    
;Print Low Nybble as Hex Digit to Console
PRHEX:  AND #$0F    ;Strip High Nybble
        CMP #$0A    ;If Low Nybble >= 10
        BCC PRHEXC  ;  
        ADC #$06    ;  Convert ':' to 'A'...
PRHEXC: ADC #$30    ;Convert to ASCII Character
        JMP PUTCHR  ;Print Hex Digit and Return

EXIT:   RTS         ;Return to BASIC

