
/* chdir.c - ryb */

#include <exec/types.h>
#include <exec/tasks.h>
#include <libraries/dosextens.h>
#include <functions.h>

#include <string.h>
#include <errno.h>

char *_GetPathFromLock (BPTR, char *, size_t);

int
chdir(path)
  char *path;
{
  BPTR fl_new, fl_old;
  UBYTE *SetName;

  fl_new = Lock(path, ACCESS_READ);
  if (fl_new == 0L) {
    errno = ENOENT;
    return -1;
  }

  /* Return an error if the lock is on a file. */

  {
    char fib_1[sizeof(struct FileInfoBlock) + 2];
    struct FileInfoBlock *fib = (struct FileInfoBlock *)
                                (((ULONG)fib_1 + 2) & ~2);

    if (Examine(fl_new, fib) == DOSFALSE ||
        fib->fib_DirEntryType <= 0) {
      UnLock(fl_new);
      errno = ENOENT;
      return -1;
    }
  }

  fl_old = CurrentDir(fl_new);
  UnLock(fl_old);

  /* Change the CLI's path name string.  KS2.0's dos.library has a
     function for doing this.  (FIXME!) */

  Forbid();     /* In case someone's watching */

  {
    struct CommandLineInterface *cli;

    cli = ((struct CommandLineInterface *)
          BADDR(((struct Process *)FindTask(0L))->pr_CLI));
    SetName = (UBYTE *)BADDR(cli->cli_SetName);
  }

  if (_GetPathFromLock(fl_new, (char *)SetName, 128) == 0L) {
    /* Big trouble */
    Permit();
    SetName[0] = 0;
    errno = ENOENT;
    return -1;
  }

  /* Convert the pathname to a BSTR */

  {
    register UBYTE *p= SetName;
    register int i;
    int len;

    len = strlen((char *) p);
    p += len;
    i = len;
    while (i-- > 0) {
      *p = *(p - 1);
      --p;
    }
    *p = len;
  }

  Permit();

  return 0;
}

