		INCLUDE	ccachdef.asm

CODE		SEGMENT BYTE PUBLIC

Cache		EQU	es:[bx].TCacheHeader

	; ClearCol proc
	;
	; In:	es:bx	TCacheHeader struc
	;	es:di	coloumn to be cleared
	;
	; Out:	es:di	next coloumn
	;	ax,cx	destroyed

ClearCol	PROC NEAR
		mov	cx, Cache.chColHeight
		xor	ax, ax
		cld
		shr	cx, 1
		rep	stosw
		jnc	SHORT @@1
		stosb
@@1:		retn
ClearCol	ENDP

	; SetupCache procedure
	;
	; In:	es:bx	TCacheHeader struc
	;	ax	start x
	;	dx	start y
	;	cx	height
	;	si	coloumn count
	;	di	color word

SetupCache	PROC NEAR
		mov	Cache.chColHeight, cx
		call	SetupProc
		mov	ax, bx
		add	ax, TYPE TCacheHeader
		mov	Cache.chStartOfs, ax
		mov	Cache.chColor, di
		mov	di, ax
		xchg	ax, si
		imul	Cache.chColHeight
		mov	cx, ax
		add	ax, si
		mov	Cache.chWrapOfs, ax
		mov	ax, BytesPerLine
		mov	Cache.chBPL, ax
		mov	ax, BkColor
		mov	Cache.chBkColor, ax
		mov	Cache.chMask, 0FFh

	; get the flush proc

		mov	ax, [FlushProc]
		mov	Cache.chFlushProc, ax

	; clear the cache

		cld
		mov	ax, 0
		shr	cx, 1
		rep	stosw
		jnc	SHORT @@1
		stosb
@@1:		retn
SetupCache	ENDP

	; SetLeftPos procedure

	; SetRightPos procedure
	;
	; In:	es:bx   TCachHeader struc
	;	ax	end pos

SetRightPos	PROC NEAR
		push	ax
		call	GotoPos
		pop	cx
		and	cl, 7
	;	mov	al, 0FFh
	;	jz     SHORT @@1

		mov	ax, 0FF00h
		shr	ax, cl
@@1:
		mov	Cache.chMask, al
		push	ax
		push	ds
		lds	si, Cache.chDest
		mov	ax, Cache.chStartCol
		call	Cache.chFlushProc
		pop	ds
		mov	Cache.chMask, 0FFh
		pop	ax
		mov	cx, Cache.chStartCol
		cmp	cx, Cache.chLeftCol
		jl	SHORT @@0
		je	SHORT @@2
		mov	Cache.chLeftMask, 0FFh
@@2:		not	al
		and	Cache.chLeftMask, al
		mov	Cache.chLeftCol, cx
@@0:		retn
SetRightPos	ENDP

	; GotoPos procedure
	;
	; In:	es:bx	TCacheHeader struc
	;	ax	horiz pixel position
	;
	; Out:	di	offset of the coloumn to write in
	;	cl	shift value

GotoPos		PROC NEAR
		mov	cl, al
		and	cl, 7
		sar	ax, 3
		mov	di, Cache.chStartOfs
		cmp	ax, Cache.chStartCol
		jle	SHORT @@1		; same col: exit

		push	cx
		mov	cx, ax
		sub	cx, Cache.chStartCol
		xchg	Cache.chStartCol, ax

		push	ds
		lds	si, Cache.chDest

@@4:		push	cx ax
		call	Cache.chFlushProc
		call	ClearCol
		Wrap	di
		pop	ax cx
		inc	ax
		loop	@@4

		pop	ds cx

		mov	WORD PTR Cache.chDest[0], si
		mov	Cache.chStartOfs, di
@@1:		retn
GotoPos		ENDP

CODE 		ENDS

		END
