/* File to implement the "chdir" command of Unix under AmigaDOS: */
/* December 1989 Eric Green, public domain.                      */

#include <stdio.h>

#include <libraries/dos.h>
#include <libraries/dosextens.h>

#ifdef LATTICE
#include <proto/dos.h>
#else
struct FileLock *Lock();
int Examine();
struct FileLock *CurrentDir();
void UnLock();
#endif

#include <exec/memory.h>

#ifdef LATTICE
#include <proto/exec.h>
#else
struct FileInfoBlock *AllocMem();
void FreeMem();
#endif

#include <errno.h>

#ifdef MANX
#ifndef ENOTDIR
#define ENOTDIR 11
#endif
#endif

#ifdef LATTICE
extern int _OSERR;

int chdir(char *);

#endif

int chdir(newpath)
  char *newpath;
{
    register struct FileLock *newdir;
    register struct FileLock *olddir = 0;

    register struct FileInfoBlock *fib;

    register int ioerr;  /* used as switch for I/O errors. */

#ifdef LATTICE
    _OSERR = 0;  /* clear it here... */
#endif

    newdir = Lock(newpath,ACCESS_READ);


/* we have to check & make sure it's really a directory.
   Else, CurrentDir will blithely let us chdir to it! */

    if (newdir) {
        /* test out the type before we do anything: */
        fib = AllocMem(sizeof(struct FileInfoBlock),
                        MEMF_CLEAR|MEMF_PUBLIC);
        ioerr = Examine(newdir,fib);
        if (ioerr==0) {
#ifdef LATTICE
            _OSERR = IoErr();
#endif
            errno=ENOTDIR; /* obviously! Since ACTION_EXAMINE
                             doesn't work. */
        } else {
           if (fib->fib_DirEntryType < 0) {
                errno=ENOTDIR;
           } else {
            olddir=CurrentDir(newdir);
            if (olddir==0) {
#ifdef LATTICE
                _OSERR = IoErr();
#endif
                errno=ENOTDIR; /* true, if moot... */
            }
          }
       }
       FreeMem(fib,sizeof(struct FileInfoBlock));

    } else {
        errno = ENOENT;
    }

    if (newdir==0 || olddir==0) {
#ifdef TEST
        printf("IoErr=%d\t",_OSERR);
#endif
       if (newdir) UnLock(newdir); /* clear up hanging lock. */
       return -1;
    }

    UnLock(olddir);  /* no longer needed? */
    return 0;
}

#ifdef TEST
void main(int,char **);

void main (argc,argv)
    int argc;
    char **argv;
{
    int result;

    result=chdir(argv[1]);

    printf("chdir = %d\n",result);
}
#endif
