/* chdir2.c (emx+gcc) -- Copyright (c) 1992-1996 by Eberhard Mattes */

#include <stdlib.h>
#include <string.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _chdir2 (const char *name)
{
  char old_drive, new_drive, *tmp;
  size_t len;
  int saved_errno;

  len = strlen (name);
  if (_trslash (name, len, 1))
    {
      tmp = alloca (len);
      memcpy (tmp, name, len - 1);
      tmp[len-1] = 0;
      name = tmp;
    }
  old_drive = _getdrive ();
  new_drive = _fngetdrive (name);
  if (new_drive != 0)
    {
      if (_chdrive (new_drive) != 0)
        return -1;
      if (name[2] == 0)         /* Change drive only */
        return 0;
    }
  if (__chdir (name) == 0)
    return 0;
  else
    {
      saved_errno = errno;
      _chdrive (old_drive);
      errno = saved_errno;
      return -1;
    }
}
