/* db unix version */

#define NULL (char *)0
#include	"types.h"
#include	"stat.h"
#include	"dir.h"

static struct	stat	d, dd;
static struct	direct	dir;
static char     *name;
static int	len;

static char	dot[]	 = ".";
static char	dotdot[] = "..";

static int	file;
static int	off = -1;

char *
getcwd(buf, length)
char *buf;
int length;
{
	len = length;
	name = buf+1;
	buf[0] = '/';

	for(;;) {
		if(stat(dot, &d) < 0) {
			return(NULL);
		}
		if ((file = open(dotdot,0)) < 0) {
			return(NULL);
		}
		if(fstat(file, &dd) < 0) {
			close(file);
			return(NULL);
		}
		if(chdir(dotdot) < 0) {
			close(file);
			return(NULL);
		}
		if(d.st_dev == dd.st_dev) {
			if(d.st_ino == dd.st_ino) {
				prname();
				chdir(buf);  /* Restore CWD */
				close(file);
				return(buf);
			}
			do
				if (read(file, (char *)&dir, sizeof(dir)) < 1) {
					close(file);
					return(NULL);
				}
			while (dir.d_ino != d.st_ino);
		}
		else do {
				if(read(file, (char *)&dir, sizeof(dir)) < 1) {
					close(file);
					return(NULL);
				}
				stat(dir.d_name, &dd);
		} while(dd.st_ino != d.st_ino || dd.st_dev != d.st_dev);
		close(file);
		if (!cat())
		    return(NULL);
	}
}

prname()
{
	close(file);
	if (off<0)
		off = 0;
	name[off] = '\0';
}

cat()
{
	register i, j;

	i = -1;
	while ((dir.d_name[++i] != 0) && (i < 14));
	if ((off+i+2) > len-1)
		return(0);
	for(j=off+1; j>=0; --j)
		name[j+i+1] = name[j];
	off=i+off+1;
	name[i] = '/';
	for(--i; i>=0; --i)
		name[i] = dir.d_name[i];
        return(1);
}
