/*---------------------------------------------------------------------
        Copyright (C) 1997, 1999 Nintendo.
        
        File            rtcgettime.c
        Coded    by     Shigeo Kimura.  Oct 14, 1997.
        Modified by     Koji Mitsunari. Oct 30, 2000.
        Comments        Real Time Clock Library
   
        $Id: rtcgettime.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 "controller.h"

#include "rtc.h"
#include "rtcint.h"

s32
osRTCGetTime(OSMesgQueue *mq, OSRTCTime *time){
  u8	buffer[8], temp[8];
  u8	status;
  s32	ret;

  /* ステータスチェック */
  ret = __osRTCGetStatus(mq, &status);

#if	1
  if (ret == 0){		/* ２度読み版 */
    ret = __osRTCRawRead(mq, RTC_ADDR_TIME, temp);
    if (ret == 0) {
      ret = __osRTCRawRead(mq, RTC_ADDR_TIME, buffer);
      if (bcmp(temp, buffer, sizeof(OSRTCTime))) {
	ret = __osRTCRawRead(mq, RTC_ADDR_TIME, buffer);
      }
      /* BCDコードを10進数に変換する。 */
      time->sec = OS_BCD_TO_DEC(buffer[0]);
      time->min = OS_BCD_TO_DEC(buffer[1]);
      time->hour = OS_BCD_TO_DEC(buffer[2]-128);
      time->day = OS_BCD_TO_DEC(buffer[3]);
      time->week = buffer[4];
      time->month = OS_BCD_TO_DEC(buffer[5]);

      if(buffer[7]){ /* 世紀ビットにより分岐 */
	time->year = 2000 + OS_BCD_TO_DEC(buffer[6]);
      } else {
	time->year = 1900 + OS_BCD_TO_DEC(buffer[6]);
      }
    }
  }
#else  /* Original Version SIGEO KIMURA */
  if (ret == 0){	/* CHLDフラグ使用版 */
    ret = __osRTCRawRead(mq, RTC_ADDR_FLAG, temp);
    if (ret == 0) {
      temp[1] |= 2;
      ret = __osRTCRawWrite(mq, RTC_ADDR_FLAG, temp);
      if (ret == CONT_ERR_RTC_BUSY) {
	ret = __osRTCRawRead(mq, RTC_ADDR_TIME, buffer);
	if (ret == CONT_ERR_RTC_BUSY) {
	  temp[1] &= ~2;
	  ret = __osRTCRawWrite(mq, RTC_ADDR_FLAG, temp);
	}
	/* BCDコードを10進数に変換する。 */
	time->sec = OS_BCD_TO_DEC(buffer[0]);
	time->min = OS_BCD_TO_DEC(buffer[1]);
	time->hour = OS_BCD_TO_DEC(buffer[2]-128);
	time->day = OS_BCD_TO_DEC(buffer[3]);
	time->week = buffer[4];
	time->month = OS_BCD_TO_DEC(buffer[5]);

	if(buffer[7]){ /* 世紀ビットにより分岐 */
	  time->year = 2000 + OS_BCD_TO_DEC(buffer[6]);
	} else if (buffer[6]) {
	  time->year = 1900 + OS_BCD_TO_DEC(buffer[6]);
	} else {
	  time->year = 2000;
	}
      }
    }
  }
#endif
  return(ret);
}
