/*************************************************************************
 *
 *    Used with ICCARM and AARM.
 *
 *    (c) Copyright IAR Systems 2006
 *
 *    File name   : clock-arch.c
 *    Description : Implementation of architecture-specific clock functionality
 *
 *    History :
 *    1. Date        : October 4, 2006
 *       Author      : Stanimir Bonev
 *       Description : Create
 *
 *    $Revision: 1.1.2.3 $
**************************************************************************/
#include "LPC23xx.h"

#include "clock-arch.h"
#include "ethernet.h"

volatile clock_time_t Ticks;

/*************************************************************************
 * Function Name: Tim0Handler
 * Parameters: none
 *
 * Return: none
 *
 * Description: Timer 0 interrupt handler
 *
 *************************************************************************/
static
void Timer1IntrHandler (void)
{
  ++Ticks;
//  T0IR_bit.MR0INT = 1;
    T1IR |= (1 << 1); 
    VICIRQStatus = 0;
}

/*************************************************************************
 * Function Name: clock_init
 * Parameters: Int32U IntrPriority
 *
 * Return: none
 *
 * Description: Timer init
 *
 *************************************************************************/
void clock_init(Int32U IntrPriority)
{
  Ticks = 0;

  // Init Time0
//  PCONP_bit.PCTIM0 = 1;
  PCONP |= (1 << 2);                        /* Enable Timer 1 CLK           */
//  T0TCR_bit.CE = 0;
  T1TCR &=~(1 << 0);                        /* Disable Counter 1            */
//  T0TCR_bit.CR = 1;
  T1TCR |= (1 << 1);                        /* Reset Counter 1              */
//  T0TCR_bit.CR = 0;
  T1TCR &=~(1 << 1);                        /* Relase Reset on Counter 1    */
//  T0CTCR_bit.CTM = 0;
  T1CTCR &=~(1 << 0) &~(1 << 1);            /* Mode: every rising PCLK edge */
  
//  T0MCR_bit.MR0I = 1;
  T1MCR |= (1 << 3);                        /* Enable Interrupt on MR1      */
//  T0MCR_bit.MR0R = 1;
  T1MCR |= (1 << 4);                        /* Enable reset on MR1          */
//  T0MCR_bit.MR0S = 0; 
  T1MCR &=~(1 << 5);                        /* Disable stop on MR1          */
  
  T1PR = 0;                                 /* set timer 1 period           */
  
  T1MR0 = SYS_GetFpclk(TIMER0_PCLK_OFFSET)/(TICK_PER_SEC);
  // init timer 0 interrupt
//  T0IR_bit.MR0INT = 1;
  T1IR |= (1 << 1);                          /* clear pending interrupt     */
  VIC_SetVectoredIRQ(Timer1IntrHandler,IntrPriority,VIC_CHAN_NUM_Timer1);
  VICIntEnable |= 1UL << VIC_CHAN_NUM_Timer1;
//  T0TCR_bit.CE = 1;
  T1TCR |= (1 << 0);                        /* Enable Counter               */
}

/*************************************************************************
 * Function Name: clock_init
 * Parameters: none
 *
 * Return: none
 *
 * Description: The current clock time, measured in system ticks
 *
 *************************************************************************/
clock_time_t clock_time(void)
{
  return(Ticks);
}
