.org 0xF800
mov sp,#STACK
call litedram_init


mov bx,#load_i2c_txt
call print

;########### SET ROM ADDRESS ############
mov al,#0x50
outb #0x61

mov ax,#0x0000 ; I2C ADDRESS
outw #0x62

mov al,#0x02 ; Write 16bit
outb #0x63

mov al,#0x00
outb #0x60


wait_send:
inb #0x62
test al,#0x02
jnz rom_fail
test al,#0x01
jnz wait_send

mov bx,#OK_loading_txt
call print

jmp read_code

rom_fail:
call rom_fail_print

;############ READ CODE ##################
read_code:

mov bx,#0xEFFF
mov di,#0x0000
rom_read_loop:
mov al,#0x07 ; Read, 8bit, ignore ack
outb #0x63

mov al,#0x00
outb #0x60

push bx
cmp di,#0x1800
jz print_10
cmp di,#0x3000
jz print_20
cmp di,#0x4800
jz print_30
cmp di,#0x6000
jz print_40
cmp di,#0x7800
jz print_50
cmp di,#0x9000
jz print_60
cmp di,#0xA800
jz print_70
cmp di,#0xC000
jz print_80
cmp di,#0xD800
jz print_90
back:
pop bx

wait_send2: inb #0x62
test al,#0x01
jnz wait_send2

inw #0x60
STOSW


dec bx
jz rom_read_end
dec bx
jz rom_read_end
jmp rom_read_loop

rom_read_end:

mov bx,#clear_code
call print

MOV AX,#0xC000
JMP AX

print_10:
mov cx,#ten_prc_txt
call print_prc
jmp back

print_20:
mov cx,#twenty_prc_txt
call print_prc
jmp back

print_30:
mov cx,#thirty_prc_txt
call print_prc
jmp back

print_40:
mov cx,#forty_prc_txt
call print_prc
jmp back

print_50:
mov cx,#fifty_prc_txt
call print_prc
jmp back

print_60:
mov cx,#sixty_prc_txt
call print_prc
jmp back

print_70:
mov cx,#seventy_prc_txt
call print_prc
jmp back

print_80:
mov cx,#eighty_prc_txt
call print_prc
jmp back

print_90:
mov cx,#ninty_prc_txt
call print_prc
jmp back

print_prc:
mov bx,#loading_rom_txt
call print
mov bx,cx
call print
ret

;#########################################
include LiteDram_init.asm

rom_fail_print:
mov bx,#rom_fail_txt
call print
hlt

print:
mov al,[bx]
cmp al,#0
je print_exit
out byte #0xA5
inc bx
jmp print
print_exit:
ret

 .BLKB 18 ; Using the text as stack space for the compiled program
STACK: ; brainfuck_mandelbrot depends on stack being at the end

load_i2c_txt: .ASCII 'Read I2C EEPROM:\0'
OK_loading_txt: .ASCII 'OK\nLoading rom  0%\r\0'
loading_rom_txt:        .ASCII 'Loading rom \0'
rom_fail_txt:       .ASCII 'FAIL\nNo i2c rom at 0x50\0'
ten_prc_txt:        .ASCII '10%\r\0'
twenty_prc_txt:     .ASCII '20%\r\0'
thirty_prc_txt:     .ASCII '30%\r\0'
forty_prc_txt:      .ASCII '40%\r\0'
fifty_prc_txt:      .ASCII '50%\r\0'
sixty_prc_txt:      .ASCII '60%\r\0'
seventy_prc_txt:    .ASCII '70%\r\0'
eighty_prc_txt:     .ASCII '80%\r\0'
ninty_prc_txt:      .ASCII '90%\r\0'
clear_code: DB 0x1B,0x5B,0x48,0x1B,0x5B,0x32,0x4a,0x00

.ORG 0xFFF0
MOV AX,#0xF800
JMP AX

.ORG 0xFFFF
DB 0x00 ;Make sure a full 64KiB image
