#include "global_time.h"


GLOBAL_TIME global_time = GLOBAL_TIME_DEFAULTS;


void init_global_time_struct(unsigned int freq_pwm)
{
	global_time.total_seconds = 0;
	global_time.microseconds = 0;
	global_time.pwm_tics = 0;
	global_time.miliseconds = 0;
	global_time.seconds = 0;
	global_time.minuts = 0;
	global_time.hours = 0;
	global_time.freq_pwm_hz = freq_pwm;
	global_time.microseconds_add = 1000000L / global_time.freq_pwm_hz;
}

#pragma CODE_SECTION(global_time_calc,".fast_run2");
void global_time_calc(GLOBAL_TIME_handle gt)
{
	gt->pwm_tics++;
	gt->microseconds += gt->microseconds_add;
	gt->miliseconds = gt->microseconds / 1000;
	if(gt->pwm_tics == gt->freq_pwm_hz)
	{
		gt->total_seconds++;
		gt->seconds++;
		gt->pwm_tics = 0;

		if(gt->seconds == 60)
		{
			gt->minuts++;
			gt->seconds = 0;

			if(gt->minuts == 60)
			{
				gt->hours++;
				gt->minuts = 0;
			}
		}
	}
}


void init_timer_sec(unsigned int *start_time)
{
	*start_time = global_time.total_seconds;
}

void init_timer_milisec(unsigned int *start_time)
{
	*start_time = global_time.miliseconds;
}

int detect_pause_sec(unsigned int wait_pause, unsigned int *old_time)
{
	unsigned long delta;
	delta = (unsigned int)((unsigned int)global_time.total_seconds - *old_time);

    if (delta>wait_pause) 
	{
	   *old_time = (unsigned int)global_time.total_seconds;
	   return 1;
	}
	else
	   return 0;
}

int detect_pause_milisec(unsigned int wait_pause, unsigned int *old_time)
{
	unsigned long delta;
	if(global_time.miliseconds >= *old_time)
	{
		delta = (unsigned int)((unsigned int)global_time.miliseconds - *old_time);
	}
	else
	{
		delta = (unsigned int)((unsigned int)global_time.miliseconds + (0xFFFFUL - *old_time));
	}

    if (delta>wait_pause) 
	{
	   *old_time = (unsigned int)global_time.miliseconds;
	   return 1;
	}
	else
	   return 0;
}