/*
    Copyright (C) 1995-1997
        Rainer Schnitker, Heeper Str. 283, 33607 Bielefeld
        email: rainer@mathematik.uni-bielefeld.de

    All rights reserved
*/

#include <rsxnt.h>

/*
    convert FILETIME (system) to local unix time
*/

static unsigned long ft2gmt(FILETIME *ft)
{
    SYSTEMTIME st;
    FILETIME localft;

    FileTimeToLocalFileTime(ft, &localft);
    FileTimeToSystemTime(&localft, &st);
    return (_rsxnt_st2gmt(&st));
}

#define MAKEPERM(x) (((x) >> 6) * 0111)

void _rsxnt_ft2stat(struct stat *statbuf, FILETIME *ct, FILETIME *at, FILETIME *mt)
{
    statbuf->st_mtime = ft2gmt(mt);

    if (ct->dwLowDateTime == 0 && ct->dwHighDateTime == 0)
        statbuf->st_ctime = statbuf->st_mtime;
    else
        statbuf->st_ctime = ft2gmt(ct);

    if (at->dwLowDateTime == 0 && at->dwHighDateTime == 0)
        statbuf->st_atime = statbuf->st_mtime;
    else {
        // Under FAT the access time has only a valid day field (time is NULL).
        // If the access and modification date is equal, use the modification time
        // to prevent that the access time is smaller than the modification time.
        FILETIME local;
        WORD m_date=0, m_time=0;
        WORD a_date=0, a_time=0;

        FileTimeToLocalFileTime(at, &local);
        FileTimeToDosDateTime(&local, &a_date, &a_time);
        FileTimeToLocalFileTime(mt, &local);
        FileTimeToDosDateTime(&local, &m_date, &m_time);

        if (a_date != m_date || a_time != 0)
            statbuf->st_atime = ft2gmt(at);
        else
            statbuf->st_atime = statbuf->st_mtime;
    }
}
