; ---- File Routines for GABasic

; ---- 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
  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
  add eax, filehandle
  mov ebx, [eax]
  mov ah, 3Eh
  INT 21h
  jc closeerror
  RET
closeerror:
  mov eax, 1
  Call NEAR EndProgram
RET

; -----------------------
; Get And Put (File Mode) 
; -----------------------
Get:
PUSH eax
SHL EAX, 1
MOV EDX, EBX
ADD EAX, filehandle
MOV BX, [EAX]
MOV AX, 3F00h
INT 21h
JC gerror
POP ebx
shl ebx, 2
add ebx, filepos
add [ebx], eax
gerror:
RET

Put:
PUSH eax
SHL EAX, 1
MOV EDX, EBX
ADD EAX, filehandle
MOV BX, [EAX]
MOV AX, 4000h
INT 21h
JC perror
POP ebx
shl ebx, 2
add ebx, filepos
add [ebx], eax
perror:
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]
RET

; ---- PRINT and LINE INPUT
; EAX - File   EBX - Dest/Src

FileInput:
  PUSH EAX
  PUSH EBX
  MOV EDI, 0
  SHL EAX, 1
  mov edx, ebx
  Add eax, filehandle
  add edx, 4
  mov ebx, [eax]
  mov ecx, 1
FNextchar:
  INC EDI
  mov ah, 3Fh
  INT 21h
    CMP ax, 0
    JE endoffile
  MOV ax, [edx-1]
  INC EDX
  CMP ax, 0A0Dh
JNE FNextchar  
  POP EBX
  POP EAX
  Call UpdatePos
  SUB edi, 2
  Mov [ebx], edi
RET
endoffile:
  POP EBX
  POP EAX
  mov [ebx], edi
RET
UpdatePos:
  SHL eax, 2
  add eax, filepos
  mov [eax], edi
RET

Fileprint:
  PUSH EAX
  shl eax, 1
  add eax, filehandle
  mov ecx, [ebx]
  cmp ecx, 0
  JE skipwrite
     mov edx, ebx
     add edx, 4
     mov bx, [eax]
     mov ah, 40h
     INT 21h
skipwrite:
  PUSH ECX
  mov ah, 40h
  mov ecx, 2
  mov edx, tmp
  mov word [tmp], 0A0Dh
  INT 21h
  POP ECX
  ADD ecx, 2
  POP eax
  shl eax, 2
  add eax, filepos
  add [eax], ecx
RET

