#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;
}

#define INITIAL_HUNDREDTHS 0u
static volatile uint32_t elapsed = INITIAL_HUNDREDTHS;

static const uint8_t digit[] = {63, 6, 91, 79, 102, 109, 125, 7, 127, 111};

static uint32_t two_digits(unsigned value)
{
    return ((uint32_t)digit[value / 10u] << 8) | digit[value % 10u];
}

static void show(unsigned count)
{
    unsigned minutes = count / 6000u;
    unsigned seconds = (count / 100u) % 60u;
    unsigned hundredths = count % 100u;
    HEX_HIGH = two_digits(minutes);
    HEX_LOW = (two_digits(seconds) << 16) | two_digits(hundredths);
}

static uint32_t next_hundredth(uint32_t current)
{
    uint32_t next = current + 1u;
    return next == 6000u /* TODO: set the full-hour limit. */ ? 0u : next;
}

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(1000000u);
        elapsed = next_hundredth(elapsed);
    } else {
        for (;;) { }
    }
}

static void enable_interrupts(void)
{
    __asm__ volatile ("csrci mstatus, 8" ::: "memory");
    __asm__ volatile ("csrw mtvec, %0" :: "r"((uintptr_t)machine_event) : "memory");
    start_interval(1000000u);
    __asm__ volatile ("csrw mie, %0" :: "r"((1u << 7)) : "memory");
    __asm__ volatile ("csrsi mstatus, 8" ::: "memory");
}

int main(void)
{
    enable_interrupts();
    for (;;) {
        show(elapsed);
    }
}
