#define F_CPU 8'000'000UL

#include <stdint.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>


volatile uint16_t timer_counter = 0;

ISR(TIMER0_COMPA_vect) {
    ++timer_counter;
}

void init_timer() {
    TCCR0A = 0b00000010;
    TCCR0B = 0b00000011;
    TCNT0 = 0;
    OCR0A = 125;
    TIMSK  = 0b00000001;
}

void stop_timer() {
    TCCR0B &= ~0b00000011;
}

void resume_timer() {
    TCCR0B |= 0b00000011;
}

uint16_t millis() {
    return timer_counter;
}

int main() {
    // Leds
    DDRB = 0x07;
    PORTB = 0x00;

    // Buttons
    DDRD = 0x00;
    PORTD = 0x10;

    init_timer();
    sei();

    bool is_stoped = 0;
    bool last_state = 1;
    uint16_t last_time = millis();
    while(true) {
        if(millis() - last_time > 4000) {
            PORTB = ~PORTB & 0x01;
            last_time = millis();
        }

        if(last_state != ((PIND & 0x10) ? true : false)) {
            _delay_ms(50);
            if(last_state != ((PIND & 0x10) ? true : false)) {
                last_state = !last_state;
                PORTB = (PORTB & 0xfd) | (last_state << 1);
                if(last_state) {
                    is_stoped = !is_stoped;
                    PORTB = (PORTB & 0xfb) | (is_stoped << 2);
                    if(is_stoped) {
                        stop_timer();
                    } else {
                        resume_timer();
                    }
                }
            }
        }
    }
}
