	;CPCBooster communication code.
	;V1.0 by Targhan/Arkos.

	;For CPC only fitted with CPC Booster. Source compatible with Winape/Maxam.

CPCB_InitCommand equ #f0
CPCB_InitConfirmedFromPC equ #80
CPCB_ReceiveCommand equ #f1
CPCB_EndCommand equ #f2

CPCB_TimeoutValue equ #1000





;Initialise CPCB, baudrate etc...,
;RET=Carry=1=ok 0=not detected.
CPCB_Init
	ld bc,#ff00
	in a,(c)
	cp 170
	jr nz,CPCBError
	inc c
	in a,(c)
	cp 85
	jr nz,CPCBError

	ld c,#04		;Setting Baudrate to 115200.
	ld a,#05
	out (c),c
	out (c),a

	ld c,#07		;Asynchronous, no Parity, 1 bit stop, 8 bits carac.
	ld a,%00000110
	out (c),c
	out (c),a

	ld c,#0b		;Enables buffer.
	in a,(c)
	set 4,a
	out (c),a

	ld c,#1c		;Reset buffer.
	xor a
	out (c),a

	scf
	ret

CPCBError or a
	ret



;Rry to communicate initilisation code with the PC. Timeout to retry.
;RET=Carry=1=ok 0=communication failed.
CPCB_InitPC
	ld a,CPCB_InitCommand
	call CPCB_SendByte

	call CPCB_GetByte
	jr nc,CPCBError			;Not carry=timeout
	cp CPCB_InitConfirmedFromPC
	jr nz,CPCBError
	scf
	ret

;Receive a byte from the CPCBooster (with a raster. Activate the right ink before !)
;RET=Carry=1=OK and A=byte   Carry=0=timeout
CPCB_GetByte
	ld bc,#7f55
	out (c),c
	ld bc,#ff1c
	ld de,CPCB_TimeoutValue
CPCBGBLp dec de
	ld a,d
	or e
	jr z,CPCBError	;Timeout
	in a,(c)
	or a
	jr z,CPCBGBLp

	inc c
	in a,(c)
;
	ld bc,#7f44
	out (c),c
	scf
	ret


;Set a byte received from the CPCBooster in the memory pointed by HL, which is incremented.
;BC must be set to #ff1c.
;RET=A=Value
CPCB_GetByteFastInMemory
	in a,(c)
	or a
	jr z,CPCB_GetByteFastInMemory
	inc c
	in a,(c)
	dec c
	ld (hl),a
	inc hl
	ret

;Send a byte to the CPCBooster.
;A=byte
CPCB_SendByte
	ld bc,#ff08
	out (c),a
	ret


;Receive HL bytes from CPCBooster in memory.
;HL=Nb bytes to receive.
;DE=Destination.
CPCB_GetXBytes
	ld a,CPCB_ReceiveCommand
	call CPCB_SendByte
	ld a,l				;Send the size to receive.
	call CPCB_SendByte
	ld a,h
	call CPCB_SendByte
CPCB_GetXBLoop
	push de
CPCB_GetXBL2 call CPCB_GetByte
	jr nc,CPCB_GetXBL2		;If Timeout, try again.
	pop de
	ld (de),a
	inc de
	dec hl
	ld a,l
	or h
	jr nz,CPCB_GetXBLoop
	ret


;When transfer is over, send the end command.
CPCB_SendEndCommand
	ld a,CPCB_EndCommand
	call CPCB_SendByte
	ret


	list
;**** End CPCBooster
	nolist