; Vesa Memory Size Detection, Copr. 1994 Matthias K”ppe

		INCLUDE	grdef.asm
		INCLUDE	grserv.asm

		PUBLIC	ld, DetermineEndSeg, CalcPageSize

CODE		SEGMENT BYTE PUBLIC

	Def_Mapping

ld		PROC NEAR
		ARG	ix: WORD = ArgSize
		push	bp
		mov	bp, sp
		mov	dx, ix
		mov	al, -1
		or	dx, dx
		jz	SHORT @@0
@@1:		inc	al
		shr	dx, 1
		jnc	@@1
@@0:		pop	bp
		retn	ArgSize
ld		ENDP

		; In:	ES:BX	Byte to be tested
		; Out:	CF 	set on error

TestByte	PROC NEAR
		cmp	es:[bx], ch
		jz	SHORT @@er
		mov	es:[bx], ch
		cmp	es:[bx], ch
		jnz	SHORT @@er
		retn
@@er:		stc
		retn
TestByte	ENDP

Prepare16	PROC NEAR
		mov	dx, 03CEh		; GC
		mov	ax, 0001h		; enable set/reset
		out	dx, ax
		mov	ax, 0003h		; data rotate
		out	dx, ax
		mov	ax, 0004h		; read map selected
		out	dx, ax
		mov	ax, 0005h		; graphics mode
		out	dx, ax
		mov	ax, 0FF08h		; bit mask
		out	dx, ax
		mov	dx, 03C4h		; SC
		mov	ax, 0102h		; map mask
		out	dx, ax
		retn
Prepare16	ENDP

Prepare256	PROC NEAR
		mov	dx, 03CEh		; GC
		mov	ax, 0001h		; enable set/reset
		out	dx, ax
		mov	ax, 0003h		; data rotate
		out	dx, ax
		mov	ax, 4005h		; graphics mode
		out	dx, ax
		mov	ax, 0FF08h		; bit mask
		out	dx, ax
		retn
Prepare256	ENDP

Pattern		EQU	10100101b

TestOut		PROC NEAR
		xor	dx, dx
@@1:            push	dx
		xor	ax, ax
		call	MapLinear
		mov	es, dx
		mov	bx, ax
		pop	dx
		inc	dx
		call	TestByte
		jnc	@@1
		dec	dx
		retn
TestOut		ENDP

DetermineEndSeg	PROC NEAR
		test	GrFlags, 1
		jnz	SHORT @@256
@@16:		call	Prepare16
		jmp	SHORT @@0
@@256:		call	Prepare256

@@0:		mov	ch, Pattern
		call	TestOut			; pattern test
		push	dx
		mov	ch, 0
		call	TestOut			; clear patterns / 2nd test
		pop	ax
		cmp	dx, ax
		jbe	SHORT @@1
		mov	dx, ax
@@1:		mov	cl, 16
		sub	cl, Granularity
		;inc	dx
		shl	dx, cl
		mov	EndSeg, dx
		mov	dx, 03C4h		; SC
		mov	ax, 0F02h		; map mask
		out	dx, ax
		retn
DetermineEndSeg	ENDP

CalcPageSize	PROC NEAR
		mov	ax, RealBytesPerLine
		mul	SizeY
		mov	cl, 16
		sub	cl, Granularity
		shl	dx, cl
		mov	cl, Granularity
		shr	ax, cl
		or	ax, dx
		inc	ax
		retn
CalcPageSize	ENDP

CODE		ENDS

		END
