;Apple 1 program initialization code for c02 programs

        SUBROUTINE  _APPLE2

;System Specific ASCII Key Mappings
DELKEY  EQU $08     ;Delete/Backspace Key (Left Arrow)
ESCKEY  EQU $1B     ;Escape/Stop Key      (Escape)
RTNKEY  EQU $0D     ;Return/Enter Key     (Return)

;Zero Page Variables (*=System Variable)
DSTPTR  EQU $06     ;Destination Pointer [Unused]
SRCPTR  EQU $08     ;Source Pointer [Unused]
STKPTR  EQU $1D     ;Stack Pointer [Unused]
RANDOM  EQU $1F     ;Random Number [Unused]
.INVFLG EQU $32     ;*Inverse Flag: $3F=Blinking, $7F=Inverse, $FF=Normal 
BLKPTR  EQU $3C     ;Block Segment Pointer [A1]
TEMP0   EQU $3E     ;Temporary Variables [A2-A3]
TEMP1   EQU $3F
TEMP2   EQU $40
TEMP3   EQU $41
TMPPTR  EQU $42     ;Temporary Pointer [A4]
USRPTR  EQU $44     ;User Pointer[A5]
RDSEED  EQU $4E     ;Random Number Seed
;           $71     ;[Temporary Register]
;           $FA-$FF ;Free Zero Page for Applications

;System Variables
SYSBFL  EQU 128     ;System Buffer Size [Max String Length]
SYSBFR  EQU $0300   ;System Buffer [Keyboard Buffer through $0380]
SYSBFP  EQU $03F6   ;System Buffer Position 
BLKLEN  EQU $03F7   ;Block Segment Length 
BLKBGN  EQU $03F8   ;Block Start Address 
BLKEND  EQU $03FA   ;Block End Address 
STKBGN  EQU $03FC   ;Stack Start Address 
STKEND  EQU $03FE   ;Stack End Address 

;I/O Locations
.KBD     EQU $C000  ;Keyboard Data
.AKD     EQU $C010  ;Keyboard Strobe Register

;Monitor Routines
PRBYTE  EQU $FDDA   ;Print Accumulator as Hexadecimal Number
PRHEX   EQU $FDE3   ;Print Low Nybble of Accumulator as Hex Digit
EXIT    EQU $03D0   ;Return to Monitor - Jump Vector to DOS warm start

        ORG $0C00   ;Safe Area for Machine Language

START:  JSR NEWLIN  ;Start On New Line
        JMP MAIN    ;Execute Program

;Poll Keyboard for Raw Character
POLKEY: INC RDSEED  ;Cycle Random Seed
        LDA #0      ;Clear Accumulator
        BIT .KBD     ;Check Keyboard Strobe Bit
        BPL POLKER  ;If Key Pressed  
        LDA .KBD     ;  Load Key Value
        STA .AKD     ;  Clear Strobe
POLKER: RTS

;Get ASCII Character from Keyboard
GETKEY: JSR POLKEY  ;Poll Keyboard
        AND #$7F    ;Strip High Bit
        RTS

;Wait for ASCII Character from Keyboard
GETCHR: JSR GETKEY  ;Get Modified Key Code
        BEQ GETCHR  ;Loop if No Key	
        RTS

;Delete Previous Character
DELCHR: LDX #2      ;Two Characters Total
        LDA #$88    ;Load Backspace Character
        JSR $F94C   ;Monitor Routine PRBLAX
        LDA #DELKEY ;Load Backspace Character
                    ;and Fall into PRCHR

;Print Character to Screen
PUTCHR: ORA #$80    ;Set High Bit
        CMP #$E0    ;
        BCC PRCHRX  ;If Lower Case 
        AND #$1F    ;  Convert to Inverse
PRCHRX: JMP $FDF0   ;Execute Monitor Routine COUT1

;Advance Character to Next line
NEWLIN   EQU $FD8E  ;Monitor Routine CROUT

        INCLUDE "putstr.a02" ;PUTSTR routine
