
#include <exec/memory.h>
#endif

#ifndef DOS_DOS_H
#include <dos/dos.h>
#endif

/* some error retcodes... */
#define FILE_NOT_FOUND (-1L)
#define NOT_ENOUGH_MEM (-2L)
#define CANNOT_EXAMINE (-3L)

/* Modified V37 struct FileInfoBlock for MultiUser, reverse-engineered */
struct muFSFileInfoBlock
{
   LONG mufib_DiskKey;
   LONG mufib_DirEntryType;
   char mufib_FileName[108];
   LONG mufib_Protection;
   LONG mufib_EntryType;
   LONG mufib_Size;
   LONG mufib_NumBlocks;
   struct DateStamp mufib_Date;
   char mufib_Comment[80];      /* Up to here, all by Commodore-Amiga, Inc. */
   WORD mufib_OwnerUID;
   WORD mufib_OwnerGID;
   char mufib_Reserved[32]; /* length is same as for standard FIB */
};
/*
   Query: Would it not be safer to store mufib_OwnerUID and mufib_OwnerGID as
   the last 2 words of mufib_FileName? (what DO they store in chars 32-107 of
   the filename, anyway?)
*/

ULONG muGetFileOwner(STRPTR filename,ULONG *errorcode)
{
    BPTR lock;
    struct muFSFileInfoBlock *fib;
    ULONG user;

    if (!(fib=(struct muFSFileInfoBlock *)
                    AllocMem(sizeof(struct muFSFileInfoBlock),
                             MEMF_PUBLIC | MEMF_CLEAR)))
    {
        *errorcode = NOT_ENOUGH_MEM;
        return NULL;
    }

    if (!(lock = Lock(filename,SHARED_LOCK)))
    {
        *errorcode = FILE_NOT_FOUND;
        FreeMem(fib,sizeof(struct muFSFileInfoBlock));
        return NULL;
    }
    
    if (!Examine(lock,fib))
    {
        UnLock(lock);
        *errorcode = CANNOT_EXAMINE;
        return NULL;
    }

    user = (fib->mufib_OwnerUID << 16) | fib->mufib_OwnerGID;
    *errorcode = NULL;

    UnLock(lock);
    FreeMem(fib,sizeof(struct muFSFileInfoBlock));

    return user;
}
