#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>

#define IsHigh(BIT, PORT)    ((PORT & (1<<BIT)) != 0)
#define IsLow(BIT, PORT)     ((PORT & (1<<BIT)) == 0)
#define SetBit(BIT, PORT)     PORT |= (1<<BIT)
#define ClearBit(BIT, PORT)   PORT &= ~(1<<BIT)

// misc

#define OUTPUT   1
#define INPUT    0

#define PWM1BIT  0
#define PWM2BIT  1
#define PWM3BIT  2
#define PWM4BIT  3

#define PWM1PORT PORTA
#define PWM2PORT PORTA
#define PWM3PORT PORTA
#define PWM4PORT PORTA

void pwmPulse(void);
void timerInit(void);

unsigned char pwmcount;
unsigned char pwm1, pwm2, pwm3, pwm4;

int main (void) {

  // set up directions 
  DDRA = (OUTPUT << PA0 | OUTPUT << PA1 |OUTPUT << PA2 |OUTPUT << PA3 |INPUT << PA4 |INPUT << PA5 |INPUT << PA6 |INPUT << PA7);
  DDRB = (INPUT << PB0 | INPUT << PB1 |INPUT << PB2 |INPUT << PB3 |INPUT << PB4 |INPUT << PB5 |INPUT << PB6 |INPUT << PB7);
  DDRC = (INPUT << PC0 | INPUT << PC1 |INPUT << PC2 |INPUT << PC3 |INPUT << PC4 |INPUT << PC5 |INPUT << PC6 |INPUT << PC7);
  DDRD = (INPUT << PD0 | INPUT << PD1 |INPUT << PD2 |INPUT << PD3 |INPUT << PD4 |INPUT << PD5 |INPUT << PD6 |INPUT << PD7);        

  pwm1 = 64;
  pwm2 = 128;
  pwm3 = 240;
  pwm4 = 255;
  
  timerInit();
  
  // chase tail
  while(1){
    
  }

}

/*********************************************************
  !!!!!!!!! SEVERLY OPTIMIZED CODE  !!!!!!!!!
   REFERNENCE ASSEMBLER OUTPUT WHEN MODIFYING
                     -O1
**********************************************************/

//void pwmPulse(void) { 
SIGNAL (SIG_OVERFLOW0) {
 if (pwmcount++ == 0){
  SetBit(PWM1BIT, PWM1PORT);
  SetBit(PWM2BIT, PWM2PORT);
  SetBit(PWM3BIT, PWM3PORT);
  SetBit(PWM4BIT, PWM4PORT);
 };

 if ((pwm1 ^ pwmcount) == 0) { ClearBit(PWM1BIT, PWM1PORT); }
 if ((pwm2 ^ pwmcount) == 0) { ClearBit(PWM2BIT, PWM2PORT); }
 if ((pwm3 ^ pwmcount) == 0) { ClearBit(PWM3BIT, PWM3PORT); }
 if ((pwm4 ^ pwmcount) == 0) { ClearBit(PWM4BIT, PWM4PORT); }
 
}

void timerInit(void) {

  // set prescaler to /1
  TCCR0 = (0 << FOC0 | 0 << WGM00 |0 << COM01 |0 << COM00 |0 << WGM01 |0 << CS02 |0 << CS01 |1 << CS00);
  
  // set interrupt mask register 
  TIMSK |= (1<<TOIE0);  
  
  // turn interrupts on
  sei();

}

