.section .text
.global _start
_start:
    li sp, 0x03fffff0
    li s0, 0x7
    li s1, 0x14
    li s2, 0x3b
    li s3, 0x7c
    li s4, 0xd7
    li s5, 0x14c
    li s6, 0x1db
    li s7, 0x284
    li s8, 0x347
    li s9, 0x424
    li s10, 0x51b
    li s11, 0x62c
    addi sp, sp, -16
    li t0, 0xff200050
    li t1, 15
    sw t1, 12(t0)
wait_key:
    li t0, 0xff200050
    lw t1, 12(t0)
    andi t1, t1, 15
    beqz t1, wait_key
    sw t1, 12(t0)
    sw t1, 4(sp)
    li t2, 0xff200040
    lw a0, 0(t2)
    li t3, 12
    bgeu a0, t3, wait_key
    sw a0, 8(sp)
    call get_reg
    sw a0, 0(sp)
    la a0, prefix
    call uart_string
    lw a0, 8(sp)
    call dec_word
    li a0, 61
    call uart_byte
    lw t1, 4(sp)
    andi t1, t1, 1
    beqz t1, decimal_output
    la a0, hex_prefix
    call uart_string
    lw a0, 0(sp)
    call hex_word
    j newline
decimal_output:
    lw a0, 0(sp)
    call dec_word
newline:
    li a0, 10
    call uart_byte
    j wait_key

get_reg:
    # TODO: return the saved register selected by a0.
    li a0, 0
    ret

# Wait for transmit space before writing a single byte from a0.
uart_byte:
    li t0, 0xff201000
uart_wait:
    lw t1, 4(t0)
    srli t1, t1, 16
    beqz t1, uart_wait
    sw a0, 0(t0)
    ret

# Walk a zero-terminated string. uart_byte may change any caller-saved register.
uart_string:
    addi sp, sp, -16
    sw ra, 12(sp)
    sw s0, 8(sp)
    mv s0, a0
string_next:
    lbu a0, 0(s0)
    beqz a0, string_done
    call uart_byte
    addi s0, s0, 1
    j string_next
string_done:
    lw s0, 8(sp)
    lw ra, 12(sp)
    addi sp, sp, 16
    ret

hex_digit:
    andi a0, a0, 15
    la t0, digits
    add t0, t0, a0
    lbu a0, 0(t0)
    j uart_byte

hex_word:
    addi sp, sp, -16
    sw ra, 12(sp)
    sw s0, 8(sp)
    sw s1, 4(sp)
    mv s0, a0
    li s1, 8
hex_next:
    srli a0, s0, 28
    call hex_digit
    slli s0, s0, 4
    addi s1, s1, -1
    bnez s1, hex_next
    lw s1, 4(sp)
    lw s0, 8(sp)
    lw ra, 12(sp)
    addi sp, sp, 16
    ret

# Build the unsigned decimal digits backwards in a private stack buffer.
dec_word:
    addi sp, sp, -32
    sw ra, 28(sp)
    mv t0, a0
    addi t1, sp, 15
    sb zero, 0(t1)
    li t2, 10
dec_next:
    remu t3, t0, t2
    divu t0, t0, t2
    addi t3, t3, 48
    addi t1, t1, -1
    sb t3, 0(t1)
    bnez t0, dec_next
    mv a0, t1
    call uart_string
    lw ra, 28(sp)
    addi sp, sp, 32
    ret

.section .rodata
digits: .asciz "0123456789ABCDEF"
prefix: .asciz "s"
hex_prefix: .asciz "0x"
