/*---------------------------------------------------------------------
        Copyright (C) 1997, 1999 Nintendo.
        
        File            rtcgetlatertime.c
        Coded    by     Shigeo Kimura.  Oct 14, 1997.
        Modified by     Koji Mitsunari. Jan 28, 1999.
        Comments        Real Time Clock Library
   
        $Id: rtcgetlatertime.c,v 1.1 2004/02/12 20:16:24 tong Exp $
   ---------------------------------------------------------------------*/
/**************************************************************************
 *
 *  $Revision: 1.1 $
 *  $Date: 2004/02/12 20:16:24 $
 *  $Source: 
 *
 **************************************************************************/
#include "osint.h"

#include "rtc.h"
#include "rtcint.h"

void __osRTCGetLaterTime(OSRTCTime *before, u32 time, OSRTCTime *after);

s32
osRTCGetLaterTime(OSMesgQueue *mq, u32 time, OSRTCTime *after){
  s32		ret;
  OSRTCTime	before;

  ret = osRTCGetTime(mq, &before); /* 現在時刻を知る */
  if(ret == 0) {
    __osRTCGetLaterTime(&before, time, after);
  }
  return(ret);
}

void
__osRTCGetLaterTime(OSRTCTime *before, u32 time, OSRTCTime *after) {
  static u16 total_month[2][13]={
    {0,31,59,90,120,151,181,212,243,273,304,334,365},
    {0,31,60,91,121,152,182,213,244,274,305,335,366}};
  static s32 total_year[4][4]={{366,731,1096,1461},
			{365,730,1095,1461},
			{365,730,1096,1461},
			{365,731,1096,1461}};
  int i;
  u32 min_dash = (u32)before->min + time; /* そのまま分同士の加算 */
  u32 hour_dash = (u32)before->hour + min_dash /60; /* 時同士の加算 */
  u32 between_day = hour_dash /24; /* 上記を日数にする */
  u8 before_leap = before->year % 4; /* 開始年が閏年か？ */
  u8 after_leap; /* 最終年が閏年か？ */
  u32 day_dash = (u32)before->day - 1 + /* 開始年の１月１日より日数を加算する。 */
    (u32)total_month[(before_leap==0)][before->month-1] + between_day;
  u16 four_years = day_dash / 1461; /* ４年間単位で割る */
  s32 surplus_days = (s32)day_dash % 1461; /* ４年単位の余りを作成 */
  u16 year; /* 最終セットまでの箱 */
  u8 min,hour,month,day,week; /* 最終セットまでの箱 */

  min = min_dash % 60;
  hour = hour_dash % 24;
  i=0;
  while((surplus_days-total_year[before_leap][i])>=0){ /* あまりの年を計算 */
    i++;
  }
  surplus_days=(i==0)?(surplus_days):
    (surplus_days-total_year[before_leap][i-1]); /* 最終年の１月１日からの日数 */
  year = before->year + four_years * 4 + (u16)i; /* 年 */
  after_leap=(((before_leap+i)%4)==0); /* その年が閏年か */

  i = 0;
  while((surplus_days-total_month[after_leap][i])>=0){ /* 月を計算 */
    i++;
  }
  surplus_days=surplus_days-total_month[after_leap][i-1];
  month = i; /* 月 */
  day = surplus_days+1; /* 日 */
  week = ((u32)before->week + between_day)%7; /* 週 */

  after->year = year;
  after->month = month;
  after->day = day;
  after->week = week;
  after->min = min;
  after->hour = hour;
  after->sec = before->sec; /* 秒はそのままコピーする */
  return;
}
