#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include "firefly.h"
#include "photoresistor.h"
#include "main.h"

unsigned int firefly_position = 0;
unsigned int firefly_charlie = 0;

// main function
int main()
{
  // setup ports
  DDRB = _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4);
  PORTB = 0;

  // setup timer
  sei();
  OCR0A = 0;
  TIMSK = _BV(OCIE0A) | _BV(TOIE0);

  // setup the fireflies
  fireflies_setup();

  // startup animation

  // main loop
  while(1)
  {
    // wait until it's dark out!
    do
    {
      sleep_8s();
    }
    while(!is_dark());

    // start timer prescaling 1:1
    TCCR0B = _BV(CS00);

    // update fireflies
    do
    {
      // seed the rand function
      srand(get_random_seed());

      // update fireflies
      fireflies_update();
    }
    while(is_dark());

    // stop timer
    TCCR0B = 0;
  }
  return 0;
}

// timer0 overflow interrupt, turn on firefly
ISR(TIM0_OVF_vect)
{
  // get firefly's brightness
  unsigned int brightness = fireflies_brightness(firefly_position);

  // skip if the brightness is 0
  if(brightness == 0)
  {
    PORTB = 0; // is this necessary?  does COMPA always turn it off?
  }
  // otherwise set the pins, output levels, and compare value
  else
  {
    PORTB = _BV(firefly_charlie + (firefly_position & 2));
    DDRB = _BV(firefly_charlie) | _BV(firefly_charlie + 1);
    OCR0A = brightness;
  }
}

// timer0 compare A interrupt, turn off led and move to next firefly
ISR(TIM0_COMPA_vect)
{
  PORTB = 0;
  if(firefly_position == FF_COUNT - 1)
  {
    firefly_position = firefly_charlie = 0;
  }
  else
  {
    if(firefly_position & 1)
      firefly_charlie++;
    firefly_position++;
  }
}
