bits 64

global __euler_open_file
global __euler_close_stream
global __euler_get_new_pages
global __euler_write_to_stream
global __euler_seek_stream
global __euler_get_stream_length
global __euler_set_stream_length
global __euler_end_this_thread
global __euler_read_from_stream
global __euler_get_framebuffer
global __euler_encode_color
global __euler_get_input_packet

section .text

__euler_open_file:
  mov rax, 2
  push rdx
  xor rdx, rdx
  or rdx, r8
  shl r9, 1
  or rdx, r9
  syscall
  pop rdx
  mov qword [rdx], rdi
  ret

__euler_close_stream:
  mov rax, 11
  syscall
  ret

__euler_get_new_pages:
  mov rax, 4
  syscall
  ret

__euler_write_to_stream:
  mov rax, 14
  syscall
  ret

__euler_seek_stream:
  mov rax, 12
  syscall
  ret

__euler_get_stream_length:
  push rsi
  mov rax, 15
  syscall
  pop rsi
  mov qword [rsi], rdi
  ret

__euler_set_stream_length:
  mov rax, 18
  syscall
  ret

__euler_end_this_thread:
  mov rax, 3
  syscall

__euler_read_from_stream:
  mov rax, 13
  syscall
  ret

__euler_get_framebuffer:
  push rdi
  push rsi
  push rdx
  mov rax, 1
  syscall
  pop rdx
  mov dword [rdx], esi
  pop rdx
  pop rsi
  mov dword [rsi], edi
  shr rdi, 32
  mov dword [rdx], edi
  ret

__euler_encode_color:
  xor ah, ah
  mov al, dl
  shl ax, 8
  mov al, sil
  shl eax, 8
  mov al, dil
  mov edi, eax
  xor rax, rax
  syscall
  ret

__euler_get_input_packet:
  push rdi
  push rsi
  push rdx
  push rcx
  mov rax, 5
  syscall

  test al, 0x80
  jnz .mouse_packet

  pop rcx
  mov dword [rcx], edi
  add rsp, 24
  mov al, 2
  ret

.mouse_packet:
  add rsp, 8
  pop rdx
  mov word [rdx], si
  pop rdx
  mov word [rdx], di
  pop rdx
  and al, 0x7f
  mov byte [rdx], al
  mov al, 1
  ret
