; Boot sector for the C128 that loads the prserver daemon automatically
; and switches the PIA memory expansion off (if present) when required

	processor 6502

	include "include/cbmrom.lib"
	include "options.inc"

	seg code
	org $b00	; the whole code must fit in $b00-$bff

	.byte "CBM"		; magic cookie
	.byte 0,0,0,0		; no other boot sector
	.byte "PRLINK",0	; program title
	.byte 0			; no filename

default = 0	; select default mode:
		; 0 to 3, 8 to 15: C128 mode, PIA not disabled
		; 4 to 7:          C128 mode, PIA disabled
		; 16 to 31:        C64 mode, PIA disabled, 1541 mode set
		; 32 to 63:        C64 mode, PIA not disabled
		; 64 to 255:       boot aborted (nothing loaded, C128 mode)

entry:
	lda #$c0
	jsr setmsg	; enable system messages
	lda $dc01	; check STOP, Q, C=, space, 2, CTRL, <- and 1
	eor #$ff
	bne nodefault$
	lda #default	; no key pressed: use the default value
nodefault$
	cmp #$40
	bcc noexit$
	rts		; STOP or Q pressed: exit to normal 128 mode
noexit$:
	cmp #$20
	bcc cont$	; C= key: switch to C64 or C2564 mode

#if ramexp & piaexp
	ldx #<file2564
	lda #f2564end-file2564
#else
	ldx #<file64
	lda #f64end-file64
#endif
	jsr loadf
	bcs abort
	bcc c64mode	; branch always

cont$:
	cmp #$10	; space bar: disable the PIA and switch to C64 mode
	bcc c128mode

#if ramexp & piaexp
	jsr piaoff	; shut off the PIA expansion
#endif
	ldx #<file64
	lda #f64end-file64
	jsr loadf
	bcs abort

	ldx fa		; reset the drive (force 1541 mode)
	lda #15
	tay
	jsr setlfs
	lda #ini1571e-init1571
	ldx #<init1571
	ldy #>init1571
	jsr setnam
	jsr open
	jsr close
c64mode:
	sei		; switch to C64 mode
	lda #0	
	sta $d030
	sta $d506
	lda #$f7
	sta $d505
	sta 1

	sec		; prepare for jump at (end address - 3)
	lda eal
	sbc #3
	sta jump$+1
	lda eah
	sbc #0
	sta jump$+2

	ldx #$ff
	txs
	jsr $fda3	; this is copied from the C64 reset routine
	jsr $fd50
	jsr $fd15
	jsr $ff5b

jump$:	jsr *		; placeholder for self-modifying code: init the program

	cli
	jmp ($a000)

init1571:
	.byte "U0>M0"
ini1571e:

c128mode:
#if ramexp & piaexp
	and #4		; CTRL key: shut off the PIA expansion
	beq skip$
	jsr piaoff
	ldx #<file128
	lda #f128end-file128
	bne launch$	; branch always
skip$:
	ldx #<file1028
	lda #f1028end-file1028
#else
	ldx #<file128
	lda #f128end-file128
#endif

launch$:
	jsr loadf
	bcs abort
	jmp (sal)	; launch the program
abort:
	rts

#if ramexp & piaexp
piaoff:
	ldx #11
loop$:	lda piatable,x
	sta pia+1,x
	dex
	bpl loop$
	rts

piatable:
	.byte $35,$fe,4,$ff,0,$ff,0,$dc,4,$fe,4
#endif

loadf:
	ldy #>file64
	jsr setnam	; set the file name,
	lda #1
	sta la		; file number and
	sta sa		; secondary address.
	lda #0
	jmp load	; load the file

;file names

file64:
	.byte "PR64"
f64end:

file128:
	.byte "PR128"
f128end:

#if ramexp & piaexp
file2564:
	.byte "PR2564"
f2564end:

file1028:
	.byte "PR1028"
f1028end:
#endif

	seg filler
	org $bff
	.byte $ff
