; ---- File Routines for Ultrabasic
; ---- Gabriel Fernandez
; ---- You are not allowed to use this code without permission

; ---- CloseAll
CloseAll:
  mov dword [curclose], 0
closeloop:
  inc dword [curclose]
  mov eax, [curclose]
  shl eax, 1
  mov bx, [eax+filehandle]
  cmp bx, 0
  JE skipclose
    mov eax, [curclose]    
    CALL CloseFile
skipclose
  cmp dword [curclose], 255
  JNGE closeloop
RET

; ---- Setfilepos
; Eax - Filenum
; Ebx - New position
Setfilepos:
  mov [temp], ebx
  mov edx, eax
  shl edx, 1
  add edx, filehandle
  mov bx, [edx]
  shl eax, 2
  add eax, filepos
  mov dx, [temp]
  mov cx, [temp+2]
  mov [eax], dx
  mov [eax+2], cx
  mov ax, 4200h
  INT 21h
  JC ErrorEndProgram
RET

; ---- Getfilepos
; EAX - Filenum
; RETS: EAX - Filepos
Getfilepos:
  mov edx, eax
  shl edx, 1
  add edx, filehandle
  mov bx, [edx]
  mov ax, 4201h
  mov ecx, 0
  mov edx, 0
  INT 21h
  mov [temp], ax
  mov [temp+2], dx
  mov eax, [temp]
RET

; ---- File Open
; EAX - Num
; EBX - String
; RETS: Nothing

OpenFile:
  PUSH EAX
  Add ebx, 4
  Mov ax, 3D03h
  Mov edx, ebx
  INT 21h
  jc CreateFile
  jmp savehandle
CreateFile:
  mov ah, 3Ch
  mov cx, 0
  INT 21h
  jc openerror
savehandle:
  POP EBX
  mov edx, ebx
  shl ebx, 1
  shl edx, 2
  mov dword [fileeof+edx], 0
  add ebx, filehandle
  add edx, filepos
  mov dword [edx], 0
  mov [ebx], ax
  RET
openerror:
  POP EAX
  mov eax, 1
  Call NEAR EndProgram
RET

; ---- File Close
; EAX - Num

CloseFile:
  shl eax, 1
  mov bx, [eax+filehandle]
  mov word [eax+filehandle], 0
  mov ah, 3Eh
  INT 21h
  jc closeerror
  RET
closeerror:
  mov eax, 1
  Call NEAR EndProgram
RET

; -----------------------
; Get And Put (Binary Mode) 
; -----------------------
FileGet:
PUSH eax
SHL EAX, 1
MOV EDX, EBX
ADD EAX, filehandle
MOV BX, [EAX]
MOV EAX, 3F00h
INT 21h

CMP EAX, 0
JNE skipgseteof
  POP ebx
  shl ebx, 2
  add [ebx+filepos], eax
  mov dword [ebx+fileeof], 1
RET
skipgseteof:
POP ebx
shl ebx, 2
add ebx, filepos
add [ebx], eax
RET

FilePut:
PUSH eax
PUSH ecx
SHL EAX, 1
MOV EDX, EBX
ADD EAX, filehandle
MOV BX, [EAX]
MOV AX, 4000h
INT 21h
POP ecx
POP ebx
CMP eax, ecx
JNE ErrorEndProgram
shl ebx, 2
add ebx, filepos
add [ebx], eax
RET

; --- Lof
; EAX: File
; Rets: Eax - Size
Lof:
  mov [s], eax
  SHL eax, 1
  add eax, filehandle
  mov bx, [eax]
  mov ax, 4202h
  xor cx, cx
  xor dx, dx
  INT 21h
  PUSH ax
  PUSH dx
  mov eax, [s]
  shl eax, 2
  add eax, filepos
  mov dx, [eax]
  mov cx, [eax+2]
  mov ax, 4200h
  INT 21h
  mov eax, s
  POP DX
  POP BX
  mov [eax], bx
  mov [eax+2], dx
  mov ebx, [eax]
  mov eax, ebx
RET

