#include "timer.h"
#include "timer_macros.h"

void timer_init(void)
{
	//// Timer0
	// prescaler
	TCCR0B &= TCCRnB_CSn_CLEAR;
	TCCR0B |= TCCR0B_CS0_prescale1;
	// interrupt mask
	TIMSK0 &= TIMSKn_ENABLE_INTERRUPT_CLEAR;
	TIMSK0 |= TIMSK0_ENABLE_INTERRUPT_on_nothing;

	//// Timer1
	// prescaler
	TCCR1B &= TCCRnB_CSn_CLEAR;
	TCCR1B |= TCCR1B_CS1_prescale256;
	// interrupt mask
	TIMSK1 &= TIMSKn_ENABLE_INTERRUPT_CLEAR;
	TIMSK1 |= TIMSK1_ENABLE_INTERRUPT_on_overflow;
	
	SREG |= 0x80;	// Status Register
					// Enable global interrupts
}

void timer_reset(void)
{
	TCNT0 		= 0;
	TCNT1 		= 0;
	highBits32 	= 0;
	highBits64 	= 0;
}

// ISR(TIMER1_OVF_vect)
void timer_overflow(void)
{
	highBits32 += 0x01000000;
	highBits64 += 0x0000000001000000;
}

uint32_t timer_now32(void)
{
	uint32_t lowBits 	= TCNT0;
	uint32_t middleBits = TCNT1;
	return highBits32 | (middleBits<<8) | lowBits;
}

uint64_t timer_now64(void)
{
	uint64_t lowBits 	= TCNT0;
	uint64_t middleBits = TCNT1;
	return highBits64 | (middleBits<<8) | lowBits;
}
