;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; WBO2 READ PATCH FOR 9396 ECM WITH BCFA CODE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; adds the ADC read subroutine from the AZTY code
; to the BCFA code for the 9396 ECM.
;
;
; also adds a read of TPS2 (pin C18) and stores it in the
; corrosivity sensor value memory byte, so that
; it comes in as data byte 44 on the ALDL stream.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Directions to compile and apply patch:
;;		AS11.EXE WBO2BCFA.ASM
;;		S19_PAT.EXE WBO2BCFA.S19 0x8000 bcfa.bin
;;
;; ATTENTION:: BCLR and BSET bit masks are NOT assembled properly to byte code.
;; They all come out as 0x00. They will need to be modified manually,
;; after applying the patch to the bin. 
;; Make the following modifications to the modified binary:
;; change 0x00 at address 0x7E34 to 0x0C
;; change 0x00 at address 0x7E67 to 0x20
;; change 0x00 at address 0x7E3E to 0x20
;;
;; You will also need to calculate the new checksum.
;; The patch cannot do this because it will be affected
;; by your specific tuning constants.
;; The checksum is the 2 bytes starting at 0x0006.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; instructs the assembler to make a listing
	OPT	l
		
;; mux'ed ADC read subroutine
;; inputs: A = channel #
;; ==========================
	ORG $FE2D	;; unused program code area
	
	PSHB
	PSHX
	LDX	#$4002	;; GPIOR
	BCLR	2,X,#0x0C	;; clear bits 2 (MUXA) and 3 (MUXB)
	BCLR	0,X,#0x20	;; clear bit 5 (MUXC)
	BITA	#4			;; check if bit 2 is set in channel
	BEQ	LAMJMP
	BSET	0,X,#0x20 ;; set bit 5 (MUXC)
LAMJMP:	ASLA		;; A<<1
	ASLA				;; A<<1
	ANDA	#$0C		;; mask: 00001100 (MUX A, MUX B in MUXR)
	ORAA	2,X		;; OR A with current MUXR value
	STAA	2,X		;; set new MUX A / MUX B settings
	LDAA	#$90		;; call ADREAD subroutine for port AN9
	JSR	$F04C		; ADREAD subroutine
	PULX
	PULB
	RTS

;; ALDL data reference change
;; ==========================
	ORG $93FF
	FCB $01
	ORG $9400
	FCB $EA

;; Call to WBO2 read
;; =================
	ORG	$B29F ;; original jsr $F53C

	JSR	$FE50 ;; jump to WBO2 read instead
	
;; WBO2 read
;; =========
	ORG	$FE50 ;; unused program code area

	PSHA			;; save A for original routine
	CLRA		 	;; A = 0. port for TPS2
	JSR 	$FE2D ;; mux'ed ADC read
	STAA	$01EA ;; store into (hopefully) unused RAM location
	PULA			;; restore A
	JMP	$F53C ;; jump to original instruction address
