/* timer.c */

#include <avr/io.h>
#include <avr/interrupt.h>

#include "common.h"
#include "timer.h"

uint8_t bounce_timer;
uint8_t button;
uint8_t button_port;

#define BOUNCE_TIMER_RESET 10

#define PIN_OUTPUT0 0
#define PIN_OUTPUT1 1

volatile uint8_t output0;
volatile uint8_t output1;
uint8_t tick;
volatile uint32_t seconds;

void timer_init(void)
{
    bounce_timer = 0;
    button = 0;
    button_port = 0;
    tick = TICKS_PER_SECOND-1;
    seconds = 0;

    TCCR0A = (1<<CTC0) | (1<<CS02); /* clk/256 */
    OCR0A = TIMER_MAX;
    TIMSK0 = (1<<OCIE0A);

    output0 = 0;
    output1 = 0;

    PORTD &= ~((1<<PIN_OUTPUT0) | (1<<PIN_OUTPUT1));
    DDRD |= (1<<PIN_OUTPUT0) | (1<<PIN_OUTPUT1);
}

ISR(TIMER0_COMPA_vect)
{
    uint8_t port;
    uint8_t old_button;
    uint8_t button_pressed;

    if (tick == 0) {
	tick = TICKS_PER_SECOND-1;
	seconds++;
    } else
	tick--;

    old_button = button_port;

    port = PIND;
    port = (~port >> 4);
/*
    if (bounce_timer)
	bounce_timer--;
    else
*/
	button_port = port;

    if (button_port != old_button)
	bounce_timer = BOUNCE_TIMER_RESET;

    button_pressed = button_port & ~old_button;
    if (button_pressed & 8)
	button = 4;
    if (button_pressed & 4)
	button = 3;
    if (button_pressed & 2)
	button = 2;
    if (button_pressed & 1)
	button = 1;

    if ((TICKS_PER_SECOND-1 - tick) < output0)
	PORTD |= (1<<PIN_OUTPUT0);
    else
	PORTD &= ~(1<<PIN_OUTPUT0);

    if ((TICKS_PER_SECOND-1 - tick) < output1)
	PORTD |= (1<<PIN_OUTPUT1);
    else
	PORTD &= ~(1<<PIN_OUTPUT1);
}
