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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/param.h>
#include <emx/syscalls.h>
#include <emx/io.h>

int _fullpath (char *dst, const char *src, int size)
{
  char drive, cwd1[MAXPATHLEN+1], cwd2[MAXPATHLEN+1];
  char *temp, c;
  int i, j, k, add_file;

  drive = _fngetdrive (src);
  if (drive == 0)
    drive = _getdrive ();
  else
    src += 2;
  i = strlen (src);
  temp = (char *)alloca (i+2+1);
  temp[0] = drive; temp[1] = ':';
  strcpy (temp+2, src);
  cwd1[0] = cwd2[0] = drive;
  cwd1[1] = cwd2[1] = ':';
  cwd1[2] = cwd2[2] = '/';
  if (__getcwd (cwd1+3, drive) != 0)
    goto failure;
  add_file = 0; k = 0;
  if (_chdir (temp) != 0)
    {
      k = _getname (temp) - temp;
      if (k == 3)
        {
          c = temp[k]; temp[k] = 0;
          if (_chdir (temp) != 0)
            goto failure;
          temp[k] = c;
        }
      else if (k > 3)
        {
          temp[k-1] = 0;
          if (_chdir (temp) != 0)
            goto failure;
        }
      add_file = 1;
    }
  j = __getcwd (cwd2+3, drive);
  if (_chdir (cwd1) != 0 || j != 0)
    goto failure;
  if (strlen (cwd2)+1 > size)
    {
      errno = ERANGE;
      goto failure;
    }
  strcpy (dst, cwd2);
  if (add_file && temp[k] != 0)
    {
      j = strlen (dst);
      if (j+1+strlen (temp+k)+1 > size)
        {
          errno = ERANGE;
          goto failure;
        }
      if (!_trslash (dst, j, 0))
        dst[j++] = '/';
      strcpy (dst+j, temp+k);
    }
  _fnslashify (dst);
  return 0;

failure:
  dst[0] = 0;
  return -1;
}
