#include "timer.h"
#include "timer_registers.h"
#include "interrupt.h"
#include "interrupt_registers.h"

const uint32_t Timer_Enable				= (1 << 1);

void Timer::Initialize (void)
{
	Disable();
	regWrite(TIMERS::T1TC, 1);
	regWrite(TIMERS::T1PD, 0);
}

void Timer::Configure(uint32_t periodInMicroSeconds, uint32_t tout0_HighTimeInMicroseconds)
{
	uint32_t periodInTicks 		= (periodInMicroSeconds * TicksPerMicrosecond);
	uint32_t highTimeInTicks	= (tout0_HighTimeInMicroseconds * TicksPerMicrosecond);
	
	regWrite(TIMERS::T1TC, (periodInTicks - highTimeInTicks));
	regWrite(TIMERS::T1PD, highTimeInTicks);
}

void Timer::Enable(void)
{
	regWrite(TIMERS::TMCON, (regRead(TIMERS::TMCON) |  Timer_Enable));
}
		
void Timer::Disable(void)
{
	regWrite(TIMERS::TMCON, (regRead(TIMERS::TMCON) & ~Timer_Enable));
}

void Timer::PolledWait(uint32_t waitForMicroseconds)
{
	bool done;
	Initialize();
	Configure(waitForMicroseconds, 10);
	regWrite(INTERRUPT::INTST, (1 << Timer1));
	Enable();	
    do 
    	done = (regRead(INTERRUPT::INTST) & (1 << Timer1)) ? true : false;
    while (!done);
}
