#include <fcntl.h>              /* for `O_RDONLY' */
#include <io.h>                 /* for `ftime', `open()', `setftime()', `close()' */
#include <stddef.h>             /* for `NULL' */
#include <time.h>               /* for `time_t', `tm', `time()', `localtime()' */

#include "utime.h"              /* for `utimbuf' */

int
utime(const char *path, const struct utimbuf *times)
{
    int fd;
    time_t modtime;
    struct tm *tm;
    struct ftime ftime;
    int rv = 0;

    /* DOS needs the file open */
    if ((fd = open(path, O_RDONLY)) == -1) {
        return -1;
    }

    /* `NULL' times means use current time */
    if (times == NULL) {
        modtime = time((time_t *) 0);
    } else {
        modtime = times->modtime;
    }

    /* DOS stores modification time only */
    tm = localtime(&modtime);

    /* convert `tm' to `ftime' structure */
    ftime.ft_tsec = tm->tm_sec / 2;
    ftime.ft_min = tm->tm_min;
    ftime.ft_hour = tm->tm_hour;
    ftime.ft_day = tm->tm_mday;
    ftime.ft_month = tm->tm_mon + 1;
    ftime.ft_year = tm->tm_year - 80;

    /* let `setftime()' do the real work */
    rv = setftime(fd, &ftime);

    /* close the file */
    (void) close(fd);

    return rv;
}
