#include <stdint.h>

#define TIMER_LOW (*(volatile uint32_t *)(uintptr_t)0xff202100u)
#define KEY_EDGES (*(volatile uint32_t *)(uintptr_t)0xff20005cu)
#define HEX3_TO_0 (*(volatile uint32_t *)(uintptr_t)0xff200020u)
#define HEX5_TO_4 (*(volatile uint32_t *)(uintptr_t)0xff200030u)
#define TICKS_PER_UPDATE 1000000u
#define INITIAL_HUNDREDTHS 0u
#define HUNDREDTHS_PER_HOUR 6000u /* TODO: wrap after one hour. */

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;
    HEX5_TO_4 = two_digits(minutes);
    HEX3_TO_0 = (two_digits(seconds) << 16) | two_digits(hundredths);
}

int main(void)
{
    unsigned position = INITIAL_HUNDREDTHS;
    unsigned running = 1;
    KEY_EDGES = 15u;
    uint32_t previous = TIMER_LOW;
    show(position);
    for (;;) {
        uint32_t now = TIMER_LOW;
        uint32_t edges = KEY_EDGES & 15u;
        if (edges != 0u) {
            KEY_EDGES = edges;
            running = !running;
            previous = now;
        }
        /* Unsigned subtraction also works across the timer's low-word wrap. */
        uint32_t ticks = now - previous;
        if (running && ticks >= TICKS_PER_UPDATE) {
            uint32_t steps = ticks / TICKS_PER_UPDATE;
            previous += steps * TICKS_PER_UPDATE;
            position = (position + steps) % HUNDREDTHS_PER_HOUR;
            show(position);
        }
    }
}
