;*************************************************************************
;
; EE Data Read/Write routines
; kg, 13 Jul '95
; 
; Routines:
;	ClearEE		Clear all 64 EE data registers
; 	MovEEw		Mov EE data pointed to by W to W
; 	MovwEE		Mov w to EE data reg pointed to by EEADR
; 	IncEEw		Increment EE address pointed to by W 
;	WaitEE		Wait unil EE no longer being written to
;*************************************************************************

; Read an EEDATA file register pointed to by W
; Return EEDATA contents in W and EEDATA
MovEEw
	PAGE1
WaitEE1	BTFSC	EECON1 - h'80',WR	; Check if busy writing
	goto	WaitEE1
	PAGE0

	movwf	EEADR			; EE Address to read

	PAGE1
	BSF	EECON1 - H'80', RD	; Read the address
	PAGE0
	MOVFW	EEDATA			; Copy contents to W
	return

;Read EE pointed to by EEADR to w 
; Zero flag set if EE ram contains value 0
ReadEEw	

	PAGE1
WaitEE2	BTFSC	EECON1 - h'80',WR	; Check if busy writing
	goto	WaitEE2
	PAGE0

	PAGE1
	BSF	EECON1 - H'80', RD	; Read the address
	PAGE0
	MOVFW	EEDATA			; Copy contents to W
	return



; Increment EE data address pointed to by w
; Return EE data after increment in w
; Z status flag set if result is zero
IncEEw
	call	MovEEw			; Read EE address	
	incf	EEDATA, w		; Increment EE data
	Call	MovwEE			; Write w to (EEADR)
	Call	WaitEE
	decf	EEDATA, f		; to work out z flag
	incf	EEDATA, f		; Set Z flag if inc results in zero
	return


; MovwEE
; Mov W to EE pointed to by EEADR 
MovwEE
	PAGE1
waitEEw	BTFSC	EECON1 - h'80',WR	; Check if busy writing
	goto	waitEEw
	PAGE0

	movwf	EEDATA			; Data to write to EE

	IntOff				; Turn off interrupts
	PAGE1				; Page 1
	BSF	EECON1 - h'80', WREN	; Allow eeprom writing
	movlw	h'55'
	movwf	EECON2 - h'80'
	MOVLW	H'AA'
	MOVWF	EECON2 - h'80'
	BSF	EECON1 - h'80', WR	; Start EE data write
	PAGE0
	IntOn				; Interrupts on again
	return

; Clear EE data registers
ClearEE
	call	WaitEE			; Wait if EE busy writing
	MOVLF	EEADR, D'64'		; 64 Registers

ClLoop	movlw	d'0'
	decf	EEADR, f		; Loop down through EE addresses
	Call	MovwEE	
	call	WaitEE			; Wait if EE busy
	movfw	EEADR			; before incrementing to next adr
	skpz
	goto	ClLoop
	return
	
; Wait if EE is busy writing	
; Does not affect W or STATUS
; Returns in page 0
WaitEE
	PAGE1
WaitEE0	BTFSC	EECON1 - h'80',WR	; Check if busy writing
	goto	WaitEE0
	PAGE0
	return