	;-----------------------------------------------------
	; place mem alocation bitmap on top of RAM
	; this will crash on damaged RAM chips
	; place this much lower (eventually under 1M)
	; if you still want to use such chips :P
	;-----------------------------------------------------
	shl	eax,16		;*65536 = max ram addr
	mov	[os_mem_ram_addr_max],eax
	mov	ebx,eax
	shr	ebx,12		;div 4096 = size of allocation bitmap
	sub	eax,ebx

	mov	[os_mem_bitmap_base],eax
	mov	[os_mem_bitmap_size],ebx
		
	mov	eax,[flag_gfx_mode]
	xor	eax,eax
	or	eax,eax
	jnz	no_text_cls



;------------------------------------
; other PC info
;------------------------------------
ram_size		dd	0	;*64k

os_mem_bitmap_base	dd	0
os_mem_bitmap_size	dd	0
os_mem_ram_addr_max	dd	0






;-------------------------------------------
; Memory alocator
; Byte search for first fit 4K chunk
;-------------------------------------------
API_Memory_Release PROC STDCALL
	USES	ecx,esi
	ARG	@@mem_handle:dword
	ARG	@@mem_size:dword

	mov	esi,[os_mem_bitmap_base]
	add	esi,[@@mem_handle]
	mov	ecx,[@@mem_size]

@@loop_free_mem:
	mov	byte ptr [esi],00h
	inc	esi
	dec	ecx
	jnz	@@loop_free_mem

	ret
ENDP

API_Memory_Get_Addr PROC STDCALL	
	ARG	@@mem_handle:dword

	;---------------------------------------
	;get memory addr from handle
	;---------------------------------------
	mov	eax,[@@mem_handle]
	shl	eax,12				;4k per alocation block
	add	eax,[os_mem_base]
	
	ret
ENDP

API_Memory_Allocate PROC STDCALL
	USES	ecx,ebx,edi
	ARG	@@nr_4k_chunks:dword

	LOCAL	@@candidate:dword

	mov	esi,[os_mem_bitmap_base]
	xor	ecx,ecx

@@loop_find_mem:
	movzx	eax,byte ptr [esi]
	or	eax,eax
	jz	@@found_free

	inc	esi
	inc	ecx
	jmp	@@loop_find_mem

@@found_free:
	;-----------------------------
	; found one free block
	; time to check for length
	;-----------------------------
	mov	edi,esi
	mov	[@@candidate],ecx
	mov	ebx,[@@nr_4k_chunks]
	
@@loop_check_size_ok:
	movzx	eax,byte ptr [edi]
	or	eax,eax
	jnz	@@not_enough

	dec	ebx
	jz	@@size_ok

	inc	edi
	inc	ecx

	jmp	@@loop_check_size_ok


@@not_enough:
	;--------------------------------
	; restart at bad position +1
	;--------------------------------
	mov	esi,edi
	inc	esi
	inc	ecx

	jmp	@@loop_find_mem


@@size_ok:
	;-------------------------
	; size is ok
	; loop to mark accupied
	;-------------------------
	mov	edi,esi
	mov	ebx,[@@nr_4k_chunks]
@@loop_mark:
	mov	byte ptr [esi],0ffh

	inc	esi

	dec	ebx
	jnz	@@loop_mark


	;-----------------------------
	; return
	; eax = mem handle
	; esi = mem addr
	;-----------------------------
	mov	eax,[@@candidate]
	shl	eax,12
	add	eax,[os_mem_base]
	mov	esi,eax

	mov	eax,[@@candidate]

	ret
ENDP
