#include <libraries/dosextens.h>
#include <functions.h>
#include <exec/memory.h>
#include <string.h>
#include <errno.h>
#include <time.h>

extern long send_packet (struct MsgPort *msgp, long type, ...);

int utime(char *filename, time_t *times)
{
    struct MsgPort *msgp;
    struct DateStamp dS;
    struct FileLock *lock, *plock;
    UBYTE *bstr;	/* BCPL: single byte count, followed by string bytes */
    char *cp;

    mtime_to_Stamp (times[1], &dS);
    if (!(bstr = (UBYTE *)AllocMem(64, MEMF_PUBLIC))) {
	errno = ENOMEM;
	return(-1);
    }
    if (!(msgp = (struct MsgPort *)DeviceProc(filename))) {
	FreeMem (bstr, 64);
	errno = ENOENT;
	return (-1);
    }
    if (!(lock = (struct FileLock *)Lock(filename, SHARED_LOCK))) {
	FreeMem (bstr, 64);
	errno = ENOENT;
	return (-1);
    }
    plock = ParentDir(lock);
    UnLock((BPTR)lock);
    if (!plock) {	/* looking at root */
	FreeMem(bstr, 64);
	errno = EACCES;
	return(-1);
    }

    /* The packet routine wants a Parent lock and a simple filename, so we
	provide one.  If there is a '/' in the name, we clip off and use bytes
	to the right of the last '/'.  If there is no '/' in the name and
        there is a ':', we clip off and use bytes to the right of the ':'.
    */
    if (!(cp = strrchr(filename, '/'))) cp = strchr(filename, ':');

    if (cp)
	cp++;
    else
	cp = filename;

    strcpy ((char *)(bstr + 1), cp);
    *bstr = strlen(cp);

    send_packet(msgp,ACTION_SET_DATE,0,(long)plock,(long)bstr >> 2,(long)&dS);

    UnLock((BPTR)plock);
    FreeMem(bstr, 64);
    return(0);
}
