;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Commodore 64 Basic Runtime File
;;
;; Include this at the TOP of your C64 program, and it will handle
;; hiding away the BASIC ROM and data and restoring it at the end.
;;
;; You will have a contiguous block of RAM from $0800 to $CF81, and
;; Zero Page access from $02 to $7F in the segment "zp".

.word $0801
.org  $0801

; BASIC program that just calls our machine language code
.scope
	.word _next, 10		; Next line and current line number
	.byte $9e," 2062",0	; SYS 2062
_next:	.word 0			; End of program
.scend

.data zp ; Zero Page memory segment.
.org $0002

.text

.scope
	; Cache BASIC zero page at top of available RAM
	ldx	#$7E
*	lda	$01, x
	sta	$CF81, x
	dex
	bne	-

	; Swap out the BASIC ROM for RAM
	lda	$01
	and	#$fe
	ora	#$06
	sta	$01

	; Run the real program
	jsr	_main

	; Restore BASIC ROM
	lda	$01
	ora	#$07
	sta	$01

	; Restore BASIC zero page
	ldx	#$7E
*	lda	$CF81, x
	sta	$01, x
	dex
	bne	-

	; Back to BASIC
	rts

_main:
	; Program follows...
.scend
