/*
    TMTime.c, Copyright  (c) by ,
    Swiss Federal Institute of Technology,
    Computer Engineering and Networks Laboratory.
 
    TOPSY -- A Teachable Operating System.
             Implementation of a tiny and simple
             micro kernel for teaching purposes.
 
    For further information, please visit http://www.tik.ee.ethz.ch/~topsy
 
    This software is provided under the terms of the GNU General Public Licence.
 
    A full copy of the GNU GPL is provided in the file COPYING found in the 
    development root of Topsy.
*/
/*
	
	File:                  $Source: /home/ruf/cvs_Topsy/cvs/Topsy/Threads/TMTime.c,v $
 	Author(s):             
 	Affiliation:           ETH Zuerich, TIK
 	Version:               $Revision: 2922 $
 	Creation Date:         
 	Last Date of Change:   $Date: 2007-03-19 17:48:52 +0100 (Mon, 19 Mär 2007) $  by: $Author: baderma $
	
*/

#include "TMClock.h"
#include "Configuration.h"

#include "TMTime.h"

/* that's what is being used as a counter */
static unsigned long tmTimeTicks;


/* this procedure is periodically called by the clock interrupt handler
 */
inline void tmTimeUpdate(void)
{
  tmTimeTicks++;
}

/* return the ticks for kernel functions (needs to be always positive) */
unsigned long k_now(void)
{
  return tmTimeTicks;
}

unsigned long secs(unsigned long tics)
{
  return tmTimeTicks / (1000 / TIMESLICE);
}

/* this is a simple init for time. if there is an RTC with battery the
 * ticks should be initialized by the RTC's value
 */
void tmTimeInit(void)
{
  tmTimeTicks = tmRTClockGetSeconds() * (1000 / TIMESLICE);
}

Error tmTimeGet(unsigned long* seconds, unsigned long* microSeconds)
{
  *seconds = tmTimeTicks / (1000 / TIMESLICE);
  *microSeconds = (tmTimeTicks % (1000 / TIMESLICE)) * (1000 * TIMESLICE);

  return TM_OK;
}


Error tmTimeSet(unsigned long seconds, unsigned long microSeconds)
{
  tmRTClockSetSeconds(seconds, microSeconds);
  tmTimeTicks = seconds * (1000 / TIMESLICE);
  tmTimeTicks += microSeconds * 1000000 / (1000 / TIMESLICE);

  return TM_OK;
}
