/* gmt2st.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include "rsxnt.h"

/*
    Converts Unix time format to SYSTEMTIME
*/

#define leap(y) \
  ((y) % 4 != 0 ? 0 : (y) % 100 != 0 ? 1 : (y) % 400 != 0 ? 0 : 1)

void _rsxnt_gmt2st(unsigned long *t, SYSTEMTIME *st)
{
    static int const mon_len[12] =
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    unsigned long t0, t1;
    unsigned long q;

    t0 = *t;
    if (t0 == (unsigned long) (-1))
        return;

    st->wMilliseconds = 0;
    st->wSecond = (int) (t0 % 60L);
    q = t0 / 60L;
    t0 = q;
    st->wMinute = (int) (t0 % 60L);
    q = t0 / 60L;
    t0 = q;
    st->wHour = (int) (t0 % 24L);
    q = t0 / 24L;
    t0 = q;

    st->wDayOfWeek = (int) ((t0 + 4) % 7);
    st->wYear = 1970;
    for (;;) {
        t1 = (leap(st->wYear) ? 366 : 365);
        if (t1 > t0)
            break;
        t0 -= t1;
        ++st->wYear;
    }
    st->wMonth = 1;
    for (;;) {
        if (st->wMonth == 2)
            t1 = (leap(st->wYear) ? 29 : 28);
        else
            t1 = mon_len[st->wMonth-1];
        if (t1 > t0)
            break;
        t0 -= t1;
        ++st->wMonth;
    }
    st->wDay = (int) t0 + 1;
}

