#include <stdint.h>
#include <stddef.h>
#include <avr/io.h>
#define F_CPU 20000000UL
#include <util/delay.h>
#include <stdbool.h>
//~ #define BAUD 9600
//~ #include <util/setbaud.h>
#include <avr/interrupt.h>

#define HUE_MAX 610
#define HUE_MIN 350
#define STEPS 8
//~ const uint32_t colorSteps = (HUE_MAX - HUE_MIN) / STEPS;
const uint32_t colorSteps = 5;

uint8_t volatile status = 0;
uint32_t volatile time = 0;
uint32_t volatile T_half = 0;
uint32_t volatile oldColor = 0;
uint32_t volatile oldTime = 0;

//~ ISR(INT0_vect) {
	//~ status = 1;
	//~ T_half = time + TCNT1;
	//~ TCNT1 = 0;		// Reset Timer/Counter1
	//~ time = 0;
	//~ PORTC += 1;
	//~ PORTC ^= 0x04;
	
//~ }

ISR(INT1_vect) {
	status = 1;
	T_half = time + TCNT1;
	TCNT1 = 0;		// Reset Timer/Counter1
	time = 0;
	oldColor = 0;
	oldTime = 0;
	PORTC ^= 1;
	PORTC &= 0x01;
	//~ PORTC ^= 0x04;
	
}

ISR(TIMER1_OVF_vect) {
	time += 0x00010000;
	//~ PORTC += 1;
	//~ PORTC ^= 0x04;
}

int main(){

    //~ PORTD |= (1 << PORTD2);    // turn On the Pull-up
    // PD2 is now an input with pull-up enabled
    

	EIMSK |= 0x02;	// External Interrupt Mask Register
					// Enable INT1 (PIN5) for interrupt
	EICRA |= 0x0c;	// External Interrupt Control Register
					// INT1 on rising edge
	
	TIMSK1 |= 0x01;	// Timer/Counter1 Interrupt Mask Register
					// Enable overflow interrupt
	TCCR1B |= 0x01;	// Timer/Counter1 Control Register B
					// Prescale Factor 1
	
	SREG |= 0x80;	// Status Register
					// Enable global interrupts
			
	//~ PCICR |= 0x04;	// Pin Change Interrupt Control Register
					//~ // Enabled PCINT[23;16] -> Pin 13,12,11,6,5,4,3,2
	//~ PCIFR |= 0x04;	// Pin Change Interrupt Flag Register
	
	//~ PCMSK2 = 0xff;	// Pin Change Mask Register 2
					//~ // Enabled PCINT[23;16] (Single Pins)
	DDRC = 0x3f;
	PORTC = 0x00;
	
	
	
	while(1) {
		uint32_t T_step = T_half / colorSteps;
		//~ uint32_t colorStep = (time + TCNT1) / T_step;
				
		//~ if (colorStep > oldColor) {
			//~ // TODO next color
			//~ PORTC += 0x02;
			//~ oldColor = colorStep;
		//~ }
		
		if(time + TCNT1 > oldTime + T_step){
			oldTime += T_step;
			PORTC += 0x02;
		}
	}
	return 0;
}
