#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)
#define MTIME_LOW REG32(0xff202100u)
#define MTIME_HIGH REG32(0xff202104u)
#define COMPARE_LOW REG32(0xff202108u)
#define COMPARE_HIGH REG32(0xff20210cu)

static void start_interval(uint32_t ticks)
{
    COMPARE_LOW = UINT32_MAX;
    COMPARE_HIGH = 0;
    MTIME_HIGH = 0;
    MTIME_LOW = 0;
    COMPARE_LOW = ticks;
}

static volatile uint32_t count;
static volatile uint32_t running = 1u;
static volatile uint32_t period = 25000000u;

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 == 0x80000007u) {
        start_interval(period);
        count += 1u; /* TODO: honor the run flag. */
    } else if (cause == 0x80000012u) {
        uint32_t edges = KEY_EDGES & 15u;
        KEY_EDGES = edges;
        running ^= 1u;
    } 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;
    start_interval(period);
    __asm__ volatile ("csrw mie, %0" :: "r"(((1u << 18) | (1u << 7))) : "memory");
    __asm__ volatile ("csrsi mstatus, 8" ::: "memory");
}

int main(void)
{
    enable_interrupts();
    for (;;) {
        LEDS = count & 1023u;
    }
}
