#include "chip.h"
#include <system_SAM3S.h>
#include "display.h"

/* Global varialbles */
volatile uint32_t SysTickCnt;         /* SysTick Counter                 */
volatile uint8_t semaphore = 0;
uint32_t aux_tickcnt;


void SysTick_Handler (void) 
{              /* SysTick Interrupt Handler (1 ms) */
    SysTickCnt++;
}

void BasicInitTC(void)
{
/* Timer Counter Clock Assignment*/
/*  TIMER_CLOCK1 - MCK/2
    TIMER_CLOCK2 - MCK/8
    TIMER_CLOCK3 - MCK/32
    TIMER_CLOCK4 - MCK/128
    TIMER_CLOCK5(1) - SLCK  
(1) Please see doc.    */
    uint32_t div;
    uint32_t tcclks;

    /** Enable peripheral clock. */
    PMC->PMC_PCER0 = 1 << ID_TC0;
    
    /** Configure TC for a ?kHz frequency and trigger on RC compare. */
    TC_FindMckDivisor(4, SystemFrequency, &div, &tcclks, SystemFrequency);

    TC_Configure(TC0, 0, tcclks | TC_CMR_CPCTRG);
    TC0->TC_CHANNEL[0].TC_RC = ( SystemFrequency / div ) / 4;   /* on RC makes interrupt */
    /* Configure and enable interrupt on RC compare */
    NVIC_EnableIRQ((IRQn_Type)ID_TC0);
    TC0->TC_CHANNEL[0].TC_IER = TC_IER_CPCS;
    
    TC_Start(TC0,0);   	    
}

/*void TC0_IrqHandler(void)
{
    volatile unsigned int dummy;*/
    /* Clear status bit to acknowledge interrupt */
   /* dummy = TC0->TC_CHANNEL[0].TC_SR;
    semaphore = 0;
} */

void Delay_us(uint32_t delayus)
{   
    uint32_t div;
    uint32_t tcclks;
    uint32_t frek;

    //frek = (1/delayus)*1000000;
    frek = 2000;
        
    /** Configure TC for a 1kHz frequency and trigger on RC compare. */
    if (TC_FindMckDivisor(frek, SystemFrequency, &div, &tcclks, SystemFrequency))
    {
        TC_Configure(TC0, 0, tcclks | TC_CMR_CPCTRG);
        TC0->TC_CHANNEL[0].TC_RC = ( SystemFrequency / div ) / 4;   /* on RC makes interrupt */
        semaphore = 1;
    }
    TC_Start(TC0,0);
    while(semaphore);
    TC_Stop(TC0,0);
}

void Delay (unsigned long tick) {          /* Delay Function*/
    uint32_t systickcnt;

    systickcnt = SysTickCnt;
    while ((SysTickCnt - systickcnt) < tick);
}

uint8_t one_sec(void)
{
    if ((SysTickCnt - aux_tickcnt) > 1000)
    {
        aux_tickcnt = SysTickCnt;
        return 1;
    }
    else 
        return 0;
}
