#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <avr/pgmspace.h>
#include <stdint.h>
#include <stdbool.h>

int main(void) {
    static uint8_t delay EEMEM;
    bool swSnel, swTraag, oldswSnel = false, oldswTraag = false;
    volatile uint16_t i;
    if (eeprom_read_byte(&delay) < 1 || eeprom_read_byte(&delay) > 5) {
        eeprom_write_byte(&delay, 2);
    }
    DDRB = 0xFF;
    PORTB = 0xFF;
    DDRA = 0x00;
    OCR0 = 36 * eeprom_read_byte(&delay);
    TCCR0 = 0x0D;
    TIMSK |= 1<<OCIE0;
    sei();
    while (1) {
        swTraag = ~PINA & 0x08; /* SW3 */
        if (swTraag != oldswTraag) {
            oldswTraag = swTraag;
            if (swTraag && eeprom_read_byte(&delay) < 5) {
                eeprom_write_byte(&delay, eeprom_read_byte(&delay) + 1);
                OCR0 = eeprom_read_byte(&delay) * 36;
            }
        }
        swSnel = ~PINA & 0x04; /* SW2 */
        if (swSnel != oldswSnel) {
            oldswSnel = swSnel;
            if (swSnel && eeprom_read_byte(&delay) > 1) {
                eeprom_write_byte(&delay, eeprom_read_byte(&delay) - 1);
                OCR0 = eeprom_read_byte(&delay) * 36;
            }
        }
        for (i = 0; i < 3000; ++i); /* anti-dender vertraging */
    }
    return 0;
}

ISR(TIMER0_COMP_vect) {
    static uint8_t patroon[] PROGMEM = {
        0x00, 0x80, 0xC0, 0x40, 0x60, 0x20, 0x30, 0x10,
        0x18, 0x08, 0x0C, 0x04, 0x06, 0x02, 0x03, 0x01, 0x00
    };
    static uint8_t j = 0;
    static bool heen = true;
    PORTB = ~pgm_read_byte(&patroon[j]);
    heen = heen ? ++j != sizeof patroon - 1 : --j == 0;
}
