;; #LAYOUT# STD *        #TAKE
;; #LAYOUT# *   KERNAL_0 #TAKE
;; #LAYOUT# *   *        #IGNORE

;
; Enable UP9600 interface support
;

; Based on UP9600 code by Daniel Dallman with Bo Zimmerman adaptations


!ifdef CONFIG_RS232_UP9600 {


up9600_enable: ; XXX adapt

	sei


	lda IRQVECT
	cmp #<ORIGIRQ
	bne INSTERR; IRQ-VECTOR ALREADY CHANGED
	lda IRQVECT+1
	cmp #>ORIGIRQ
	bne INSTERR; IRQ-VECTOR ALREADY CHANGED
	lda NMIVECT
	cmp #<ORIGNMI
	bne INSTERR; NMI-VECTOR ALREADY CHANGED
	lda NMIVECT+1
	cmp #>ORIGNMI
	bne INSTERR; NMI-VECTOR ALREADY CHANGED
	ldy #0
	sty RODBE
	sty RODBS
	sty RIDBE
	sty RIDBS
	;  PROBE FOR RS232 INTERFACE
	cli
	lda #$7F
	sta CIA2_ICR ; $DD0D ; DISABLE ALL NMIS
	lda #$80
	sta CIA2_DDRB ; $DD03 ; PB7 USED AS OUTPUT
	sta $DD0E; STOP TIMERA
	sta CIA2_CRB ; $DD0F ; STOP TIMERB
	bit CIA2_ICR ; $DD0D ; CLEAR PENDING INTERRUPTS
	ldx #8
INSTALL2:
	stx CIA2_PRB ; $DD01; TOGGLE TXD
	sta CIA2_PRB ; $DD01; AND LOOK IF IT TRIGGERS AN
	dex; SHIFT-REGISTER INTERRUPT
	bne INSTALL2
	lda CIA2_ICR ; $DD0D ; CHECK FOR BIT3 (SDR-FLAG)
	and #8
	beq INSTERR; NO INTERFACE DETECTED
	;  GENERATE LOOKUP TABLE
	ldx #0
INSTALL3:
	stx OUTSTAT; OUTSTAT USED AS TEMPORARY VARIABLE
	ldy #8
INSTALL4:
	asl OUTSTAT
	ror
	dey
	bne INSTALL4
	sta REVTAB,X
	inx
	bpl INSTALL3





	sei
	; XXX set NEWIRQ as IRQ vector
	; XXX set NMIDOBIT as NMI vector

	ldx TVSFLG; PAL OR NTSC VERSION PRINT
	lda ILOTAB,X; (KEYSCAN INTERRUPT ONCE EVERY 1/64 SECOND)
	sta CIA1_TIMBLO ; $DC06 ; (SORRY THIS WILL BREAK CODE, THAT USES
	lda IHITAB,X; THE TI$ - VARIABLE)
	sta CIA1_TIMBHI ; $DC07 ; START VALUE FOR TIMER B (OF CIA1)
	txa
	asl
	eor #$33; ** TIME CONSTANT FOR SENDER **
	ldx #0; 51 OR 55 DEPENDING ON PAL/NTSC VERSION
	sta CIA1_TIMALO ; $DC04 ; START VALUE FOR TIMERA (OF CIA1)
	stx CIA1_TIMAHI ; $DC05 ; (TIME IS AROUND 1/(2*BAUDRATE) )
	asl; ** TIME CONSTANT FOR RECEIVER **
	ora #1; 103 OR 111 DEPENDING ON PAL/NTSC VERSION
	sta CIA2_TIMBLO ; $DD06 ; START VALUE FOR TIMERB (OF CIA2)
	stx CIA2_TIMBHI ; $DD07 ; (TIME IS AROUND 1/BAUDRATE )
	lda #$41; START TIMERA OF CIA1, SP1 USED AS OUTPUT
	sta CIA1_CRA ; $DC0E ; GENERATES THE SENDER'S BIT CLOCK
	lda #1
	sta OUTSTAT
	sta CIA1_ICR ; $DC0D ; DISABLE TIMERA (CIA1) INTERRUPT
	sta CIA1_CRB ; $DC0F ; START TIMERB OF CIA1 (GENERATES KEYSCAN IRQ)
	lda #$92; STOP TIMERB OF CIA2 (ENABLE SIGNAL AT PB7)
	sta CIA2_CRB ; $DD0F 
	lda #$98
	bit CIA2_ICR ; $DD0D ; CLEAR PENDING NMIS
	sta CIA2_ICR ; $DD0D ; ENABLE NMI (SDR AND FLAG) (CIA2)
	lda #$8A
	sta CIA1_ICR ; $DC0D ; ENABLE IRQ (TIMERB AND SDR) (CIA1)
	lda #$FF
	sta CIA2_PRB ; $DD01; PB0-7 DEFAULT TO 1
	sta CIA1_SDR ; $DC0C ; SP1 DEFAULTS TO 1
	sec
	lda RIDBE
	sbc RIDBS
	cmp #200
	bcc ENABLE2;; DON'T ENABLE RTS IF REC-BUFFER IS FULL
	lda #2;; ENABLE RTS
	sta CIA2_DDRB ; $DD03 ;; (THE RTS LINE IS THE ONLY OUTPUT)
ENABLE2:
	cli
	pla
	tay
	pla
	tax
	pla
	rts




INSTERR:
	cli
	sec
	rts
}

