/*
 * localtime.c - localtime()

    This file is part of libRILc, a standard C library for GCC on Amiga OS.
    Copyright © 1998  Rask Ingemann Lambertsen

    This 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.

    This 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 this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, if you link this library with files compiled
    with a GNU compiler to produce an executable, this does not cause the
    resulting executable to be covered by the GNU General Public License.
    This exception does not however invalidate any other reasons why the
    executable file might be covered by the GNU General Public License.
*/

#include <utility/date.h>
#include <time.h>

#ifdef __PPC__
#include <ppcproto/utility.h>
#else
#include <proto/utility.h>
#endif

#include "internal/systemcalls.h"

static struct tm tmbuf;
static struct ClockData clkbuf;

/* Number of days between Jan 1 and the first of each month. */
int yday[12] =
{
  0, 31, 31 + 27, 31 + 27 + 31, 31 + 27 + 31 + 30, /* Jan - May */
  31 + 27 + 31 + 30 + 31, 31 + 27 + 31 + 30 + 31 + 30, /* Jun - Jul */
  31 + 27 + 31 + 30 + 31 + 30 + 31, /* Aug */
  31 + 27 + 31 + 30 + 31 + 30 + 31 + 31, /* Sep */
  31 + 27 + 31 + 30 + 31 + 30 + 31 + 31 + 30, /* Oct */
  31 + 27 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, /* Nov */
  31 + 27 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 /* Dec */
};

struct tm *localtime (time_t *tloc)
{
  __syscall_handle sh;

  if (tloc)
  {
    /* Convert the time format. */
    /* Seconds between Jan 1st 1970 and Jan 1st 1978: 252460800 */
    sh = __syscall_start ();
    Amiga2Date (*tloc - 252460800, &clkbuf);
    __syscall_end (sh);

    tmbuf.tm_sec  = clkbuf.sec;
    tmbuf.tm_min  = clkbuf.min;
    tmbuf.tm_hour = clkbuf.hour;
    tmbuf.tm_mday = clkbuf.mday;
    tmbuf.tm_mon  = clkbuf.month - 1;
    tmbuf.tm_year = clkbuf.year + (1978 - 1900);
    tmbuf.tm_wday = clkbuf.wday;

    tmbuf.tm_yday = yday[tmbuf.tm_mon] + clkbuf.mday -
    /* Take non-leap years into account. */
                    tmbuf.tm_mon >= 2 &&
                    (((clkbuf.year + 1978) %   4 == 0   &&
                      (clkbuf.year + 1978) % 100 != 0 ) ||
                      (clkbuf.year + 1978) % 400 == 0    ) ? 0 : 1;

    tmbuf.tm_isdst = -1; /* Unknown. */
  }

  return (&tmbuf);
}
