/* Copyright (C) 1991-99 Free Software Foundation, Inc.

   This file is part of GNU Pascal Library.

   Time and date routines for Extended Pascal   

The GNU Pascal Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

The GNU Pascal Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with the GNU Pascal Library; see the file COPYING.LIB.  If
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.  */

#include "rts.h"

#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif

void
_p_unix_time_to_time (time, Year, Month, Day, Hour, Minute, Second)
UnixTimeType time;
int *Year, *Month, *Day, *Hour, *Minute, *Second;
{
  time_t seconds = (time_t) time;
  struct tm *gnu = localtime (&seconds);
  *Year   = gnu->tm_year;
  *Month  = gnu->tm_mon + 1; /* 1 = January */
  *Day    = gnu->tm_mday;
  *Hour   = gnu->tm_hour;
  *Minute = gnu->tm_min;
  *Second = gnu->tm_sec;
  if (*Year < 1000) *Year += 1900;
}

UnixTimeType
_p_time_to_unix_time (Year, Month, Day, Hour, Minute, Second)
int Year, Month, Day, Hour, Minute, Second;
{
  struct tm gnu; /* It is a trademark after all }:--)= */
  memset (&gnu, 0, sizeof (gnu));
  gnu.tm_isdst = -1;
  gnu.tm_year  = Year - 1900;
  gnu.tm_mon   = Month - 1; /* 1 = January */
  gnu.tm_mday  = Day;
  gnu.tm_hour  = Hour;
  gnu.tm_min   = Minute;
  gnu.tm_sec   = Second;
  return (UnixTimeType) mktime (&gnu);
}

UnixTimeType
_p_get_unix_time (MicroSecond)
int *MicroSecond;
{
#ifdef HAVE_GETTIMEOFDAY
  struct timeval tval;
  if (!gettimeofday (&tval, 0))
    {
      if (MicroSecond) *MicroSecond = tval.tv_usec;
      return tval.tv_sec;
    }
  else
#endif
    if (MicroSecond) *MicroSecond = 0;
    return - 1;
}
