[extern _vbe_infoblock]
vbe_init:
.init_video:
;getting edid

mov ax, 0
mov es, ax
mov di, 0x500

mov ax, 0x4f15
mov bx, 0x1
mov cx, 0 
mov dx, 0

int 0x10

cmp al, 0x4f
jne .vbe_unsupported
cmp ah, 0x00
jne .edid_error


mov ah, [0x500+58]
shr ah, 4
mov al, [0x500+56]
push ax

mov ah, [0x500+61]
shr ah, 4
mov al, [0x500+59]
push ax

mov al, BYTE [0x500+20]
test al, 0x80
jz .res_unsupported ; uses an analog signal

shr al, 4
and al, 7

.cdp_6:
cmp al, 0b001
jne .cdp_8
mov ax, 18
jmp .colordepth_found

.cdp_8:
cmp al, 0b010
jne .cdp_10
mov ax, 24
jmp .colordepth_found

.cdp_10:
cmp al, 0b011
jne .cdp_12
mov ax, 30
jmp .colordepth_found

.cdp_12:
cmp al, 0b100
jne .cdp_14
mov ax, 36
jmp .colordepth_found

.cdp_14:
cmp al, 0b101
jne .cdp_16
mov ax, 42
jmp .colordepth_found

.cdp_16:
cmp al, 0b110
jne .cdp_undefined
mov ax, 48
jmp .colordepth_found

.cdp_undefined:
mov ax, 24
; TODO print warning, this only happens when we can't find bitdepth

.colordepth_found:
push ax




; _______________________________________________________________________________________________________

; When we get things sorted out, some time you should come back here and find a good resolution that isn't
; native as a fallback.
; Maybe redo this part in C?

;getting available modes
mov ax, 0
mov es, ax
mov ax, 0x500 
mov di, ax

;get vbe capabilities
mov ax, 0x4f00
int 0x10
cmp ax, 0x4f
jne .vbe_generic_error
cmp DWORD [0x500], "VESA"
jne .vbe_generic_error

; now we loop through the modes
mov ebx, [0x500+14] ; pointer to modes
mov di, 0x600
mov ax, 0
mov es, ax
.mode_loop:
mov ax, 0x4f01 
mov cx, [ebx]
cmp cx, 0xffff
je .res_unsupported

int 0x10

mov ax, [esp]
cmp al, BYTE [0x600+25] ; might be wrong
jne .mode_loop_next

; width (1920)
mov ax, [esp+4]
cmp ax, [0x600+18]
jne .mode_loop_next

; height
mov ax, [esp+2]
cmp ax, [0x600+20]
jne .mode_loop_next



jmp .mode_found

.mode_loop_next:
add ebx, 2
jmp .mode_loop
 
.mode_found:
mov ax, 0x4f02 
mov bx, cx
int 0x10
;getting rid of stack
pop ax
pop ax
pop ax
ret
; ________________________________________________________________________________________________________

.vbe_unsupported:
mov bx, .unsupported_msg
mov cx, 0
call bios_print
jmp $

.vbe_generic_error:
mov bx, .lazyerror_msg
mov cx, 0
call bios_print
jmp $

.edid_error:
mov bx, .ediderror_msg
mov cx, 0
call bios_print
jmp $

.res_unsupported:
mov bx, .res_unsupported_msg
mov cx, 0
call bios_print
jmp $

.unsupported_msg: db "Your BIOS doesn't support VESA. It's probably time to get a new computer!", 0
.lazyerror_msg: db "A VESA error has occured.", 0
.ediderror_msg: db "EDID error", 0
.res_unsupported_msg: db "Native resolution not supported!", 0
