include "m8c.inc"

ENABLE: 	equ 0x80
DI: 		equ 0x40
RW: 		equ 0x20
RST: 		equ 0x10
CS2: 		equ 0x8
CS1: 		equ 0x4
GLCD_BUSY: 	equ 0x80
GLCD_RESET: equ 0x10

export _GLCD_WriteInstruction
export _GLCD_WriteData
export _GLCD_ReadData
export _GLCD_ReadStatus
export _GLCD_WaitUntilNotBusy

; A contains the data 										
; X contains chipsel										
_GLCD_WriteInstruction:								
	PUSH A
	MOV A, X
	CALL _GLCD_WaitUntilNotBusy
	POP A
	
	M8C_SetBank1			;  configure databus as output	
	MOV REG[PRT2DM0], 255									
	MOV REG[PRT2DM1], 0										
	M8C_SetBank0
										
	MOV REG[PRT2DR], A	; put appropriate data on bus									
			
	MOV A, X
	
	OR A, (RST)
	MOV REG[PRT1DR], A
	
	OR REG[PRT1DR], (ENABLE | RST)
	NOP
	
	AND REG[PRT1DR], ~ENABLE
	
	ret														


_GLCD_WriteData:										
	PUSH A
	MOV A, X
	CALL _GLCD_WaitUntilNotBusy
	POP A
	
	M8C_SetBank1			;  configure databus as output		
	MOV REG[PRT2DM0], 255									
	MOV REG[PRT2DM1], 0										
	M8C_SetBank0
										
	MOV REG[PRT2DR], A	; put appropriate data on bus									
			
	MOV A, X
	
	OR A, (RST | DI)
	MOV REG[PRT1DR], A
	
	OR REG[PRT1DR], (ENABLE | RST | DI)
	NOP
	
	AND REG[PRT1DR], ~ENABLE
		
	RET	

_GLCD_ReadData:

; GLCD_WaitUntilNotBusy will do this for us.
;	OR F,16				; configure databus as input
;	MOV REG[PRT2DM0], 0									
;	MOV REG[PRT2DM1], 255
;  	AND F, 239
	
	PUSH A
	CALL _GLCD_WaitUntilNotBusy
	POP A
		
	OR A, (RST | DI | RW)
	MOV REG[PRT1DR], A
	
	OR REG[PRT1DR], (RST | DI | RW | ENABLE)
	
	MOV A, REG[PRT2DR]	; load the data from the bus
	
	AND REG[PRT1DR], ~ENABLE
	
	RET

; preserves X register
; trashes A
_GLCD_ReadStatus:
	M8C_SetBank1				; configure databus as input
	MOV REG[PRT2DM0], 0									
	MOV REG[PRT2DM1], 255
	M8C_SetBank0
	
	OR A, (RST | RW)
	MOV REG[PRT1DR], A
	
	OR REG[PRT1DR], (RST | RW | ENABLE)

	MOV A, REG[PRT2DR]	; load the data from the bus
	
	AND REG[PRT1DR], ~ENABLE
	RET			

; A is the chipsel
_GLCD_WaitUntilNotBusy:
	M8C_SetBank1				; configure databus as input
	MOV REG[PRT2DM0], 0									
	MOV REG[PRT2DM1], 255
	M8C_SetBank0
	
	OR A, (RST | RW)
	MOV REG[PRT1DR], A
	
StillBusyLoop:

	OR REG[PRT1DR], (RST | RW | ENABLE)

	MOV A, REG[PRT2DR]	; load the data from the bus
	AND REG[PRT1DR], ~ENABLE

	AND A, (GLCD_BUSY | GLCD_RESET)			; Look at busy flag
	JNZ StillBusyLoop

	RET	
			
