; -------- Mem Handling functions for Ultrabasic --------
; Win32 Version
; ---- You are not allowed to use this code without permission
; Gabriel Fernandez 2000

; I hope this works, first time i work on Windows

; *------------ AllocBlock
; IN: EAX = Size
; RET: EAX = Linear Address
;      SI:DI = Handle

AllocBlock:
  PUSH EAX
  PUSH DWORD GMEM_MOVEABLE | GMEM_ZEROINIT

  CALL [GlobalAlloc]
  CMP EAX, 0
  JE NEAR ErrorEndProgram
  MOV [tmp], EAX
  PUSH EAX

  CALL [GlobalLock]
  CMP EAX, 0
  JE NEAR ErrorEndProgram

  MOV SI, [tmp]
  MOV DI, [tmp+2]
RET

AllocBlockw:                          ; Windows version, like 5 clocks faster
  PUSH EAX
  PUSH DWORD GMEM_MOVEABLE | GMEM_ZEROINIT
  CALL [GlobalAlloc]
  CMP EAX, 0
  JE NEAR ErrorEndProgram

  MOV EBX, EAX
  PUSH EAX
  CALL [GlobalLock]
  CMP EAX, 0
  JE NEAR ErrorEndProgram
RET

; END AllocBlock -------------*

; *------------ ChangeBlockSize
; IN: EAX = New Size      SI:DI = Old Handle
; RET: EAX = New Linear Address
;      SI:DI = New Handle

ChangeBlockSize:
;  mov ax, 2
;  CALL NEAR EndProgram
  PUSH DWORD GMEM_MOVEABLE ;| GMEM_ZEROINIT
  PUSH EAX

  MOV [tmp], SI
  MOV [tmp+2], DI
  PUSH DWORD [tmp]
  CALL [GlobalReAlloc]
  CMP EAX, 0
  JE NEAR ErrorEndProgram
  MOV [tmp], EAX
  PUSH EAX

  CALL [GlobalLock]
  CMP EAX, 0
  JE NEAR ErrorEndProgram

  MOV SI, [tmp]
  MOV DI, [tmp+2]
RET
; END ChangeBlockSize -------------*


; *------------ FreeBlock
; IN: EBX = Handle to free, EAX = Offset
FreeBlock:
  PUSH EBX
  Call [GlobalUnlock]
  PUSH EBX
  Call [GlobalFree]
RET
; END FreeBlock -------------*

; Clearblock
; EAX = Offset, EBX = Size
Clearblock:
  MOV EDX, EAX
  ADD EDX, EBX
cloop1:
  MOV DWORD [EAX], 0
  ADD EAX, 4
  CMP EAX, EDX
  JNGE cloop1

  SUB EAX, 4
  INC EDX
cloop2:
  MOV BYTE [EAX], 0
  INC EAX
  CMP EAX, EDX
  JNE cloop2
RET

