ifndef                  _FILES_ASM
_FILES_ASM              equ     1

; ------------------------------------------------------
; Name: Load_File()
; Desc: Open a file and load it into memory
Load_File               proc    FName:dword, Read_Bytes:dword
                        local   FHandle:dword
                        local   FSize:dword
                        local   FPosition:dword

                        mov     FPosition, 0
                        invoke  CreateFile, FName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0
                        inc     eax
                        je      Error_LoadFile
                        dec     eax
                        mov     FHandle, eax
                        invoke  GetFileSize, eax, 0
                        inc     eax
                        je      Error_LoadFile
                        dec     eax
                        mov     FSize, eax
                        inc     eax                             ; Append a 0 char
                        mov     eax, ALLOCMEM(eax)
                        test    eax, eax
                        jz      Error_LoadFile
                        mov     FPosition, eax
                        invoke  ReadFile, FHandle, FPosition, FSize, Read_Bytes, 0
                        .if     eax == 0
                                FREEMEM FPosition
                                mov     FPosition, 0
                        .endif
                        invoke  CloseHandle, FHandle
Error_LoadFile:         mov     eax,FPosition                   ; Return the memory block address or 0
                        ret
Load_File               endp

; ------------------------------------------------------
; Name: Save_File()
; Desc: Save a memory block into a file
Save_File               proc    FName:dword, MemPos:dword, FSize:dword
                        local   FHandle:dword
                        local   FRealWritten:dword

                        mov     FRealWritten, 0
                        invoke  DeleteFile, FName               ; Delete it before overwriting
                        invoke  CreateFile, FName, GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_ATTRIBUTE_ARCHIVE or FILE_FLAG_RANDOM_ACCESS, 0
                        inc     eax
                        je      Error_SaveFile
                        dec     eax
                        mov     FHandle,eax
                        invoke  WriteFile, FHandle, MemPos, FSize, addr FRealWritten, 0
                        invoke  CloseHandle, FHandle
Error_SaveFile:         mov     eax,FRealWritten
                        ret
Save_File               endp

; ------------------------------------------------------
; Name: Free_File()
; Desc: Free an allocated block of memory for a file
;       (Just there for clarity purpose)
Free_File               proc    FMem:dword
                        FREEMEM FMem
                        ret
Free_File               endp

endif