    .equ BUTTON_PORT, 0xff200050
    .equ SWITCH_PORT, 0xff200040
    .equ LED_PORT, 0xff200000
    .equ DIGITS, 0xff200020
    .equ BUTTON_IRQ, 0x40000
    .text
    .global _start
_start:
    li sp, 0x03fffff0
    li s0, SWITCH_PORT
    li s1, LED_PORT
    li s2, DIGITS
    li s3, BUTTON_PORT
    sw zero, 0(s2)
    li t0, 15
    sw t0, 12(s3)            # Clear old events before unmasking the port.
    sw t0, 8(s3)
    la t0, snapshot_trap
    csrw mtvec, t0
    li t0, BUTTON_IRQ
    csrs mie, t0
    csrsi mstatus, 8

mirror:
    lw a0, 0(s0)
    sw a0, 0(s1)
    j mirror

    .balign 4
snapshot_trap:
    addi sp, sp, -16
    sw t0, 0(sp)
    sw t1, 4(sp)
    csrr t0, mcause
    li t1, 0x80000012        # Machine interrupt, button port line 18.
    bne t0, t1, unexpected
    lw t0, 12(s3)
    sw t0, 12(s3)            # Acknowledge the latched event.
    lw t1, 0(s0)
    sw zero, 0(s2)           # TODO: write the switch sample to the display.
    lw t1, 4(sp)
    lw t0, 0(sp)
    addi sp, sp, 16
    mret
unexpected:
    j unexpected
