#include <stdint.h>
#define REG32(address) (*(volatile uint32_t *)(uintptr_t)(address))
#define LEDS REG32(0xff200000u)
#define SWITCHES REG32(0xff200040u)
#define HEX_LOW REG32(0xff200020u)
#define HEX_HIGH REG32(0xff200030u)
#define KEY_MASK REG32(0xff200058u)
#define KEY_EDGES REG32(0xff20005cu)

void machine_event(void) __attribute__((interrupt("machine"), aligned(4)));
void machine_event(void)
{
    uint32_t cause;
    __asm__ volatile ("csrr %0, mcause" : "=r"(cause));
    if (cause == 0x80000012u) {
        uint32_t edges = KEY_EDGES & 15u;
        KEY_EDGES = edges;
        HEX_LOW = 0; /* TODO: capture the seven switch-controlled segment bits. */
    } else {
        for (;;) { }
    }
}

static void enable_interrupts(void)
{
    __asm__ volatile ("csrci mstatus, 8" ::: "memory");
    __asm__ volatile ("csrw mtvec, %0" :: "r"((uintptr_t)machine_event) : "memory");
    KEY_MASK = 0u;
    KEY_EDGES = 15u;
    KEY_MASK = 15u;
    __asm__ volatile ("csrw mie, %0" :: "r"((1u << 18)) : "memory");
    __asm__ volatile ("csrsi mstatus, 8" ::: "memory");
}

int main(void)
{
    HEX_LOW = 0;
    HEX_HIGH = 0;
    enable_interrupts();
    for (;;) {
        LEDS = SWITCHES & 1023u;
    }
}
