/*
 * timer.c
 *
 *  Created on: Feb 24, 2016
 *      Author: ucart
 */



#include "timer.h"

XTime before = 0, after = 0;
XTmrCtr axi_timer;
float LOOP_TIME;
float time_stamp = 0;

int timer_init()
{

	// using a axi_timer core because we've had problems with the Global Timer
	return XTmrCtr_Initialize(&axi_timer, XPAR_AXI_TIMER_0_DEVICE_ID);
}

int timer_start_loop()
{
	//timing code
	LOOP_TIME = ((float)(after - before)) / ((float) COUNTS_PER_SECOND);
	XTime_GetTime(&before);
	XTmrCtr_Reset(&axi_timer, 0);
	XTmrCtr_Start(&axi_timer, 0);

	return 0;
}

int timer_end_loop(log_t *log_struct)
{
	// get number of useconds its taken to run the loop thus far
	int usec_loop = XTmrCtr_GetValue(&axi_timer, 0) / (PL_CLK_CNTS_PER_USEC);

	// attempt to make each loop run for the same amount of time
	while(usec_loop < DESIRED_USEC_PER_LOOP)
	{
		usec_loop = XTmrCtr_GetValue(&axi_timer, 0) / (PL_CLK_CNTS_PER_USEC);
	}

//	static int counter = 0;
//	counter++;
//	if(counter % 50 == 0)
//		printf("usec_loop: %d\n", usec_loop);

	//timing code
	XTime_GetTime(&after);
	time_stamp += LOOP_TIME;
	XTmrCtr_Stop(&axi_timer, 0);

	// for timing debugging, its a separate hardware PL timer not associated with the PS
	// used this to compare to the PS clock to make sure the timing matched
//	float axi_timer_val = ((float)XTmrCtr_GetValue(&axi_timer, 0)) / ((float)100000000);


	// Log the timing information
	log_struct->time_stamp = time_stamp;
	log_struct->time_slice = LOOP_TIME;

	return 0;
}

u32 timer_get_count() {
	return XTmrCtr_GetValue(&axi_timer, 0);
}