/*
 * Return working (current) directory name.
 */
# include	<stdio.h>
# include	<sys/param.h>
# include	<sys/stat.h>
# include	<sys/dir.h>

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

static char	*
pname(s,n)
register char	*s,*n;
	{

	cat(s,"/",n,(char *) 0);

	n = s;

	while (*(s + 1) != '\0')
		s++;

	if (*s == '/' && s > (n + 1))
		*s = '\0';

	return (n);
}

char	*
curdir(str)
char	*str;
{
	int rdev, rino;
	char	name[512];
	int	file;
	int	off	= -1;
	struct	stat	d, dd;
	struct	direct	dir;
	extern char	*pname();

	stat("/", &d);
	rdev = d.st_dev;
	rino = d.st_ino;
	for (;;) {
		stat(dot, &d);
		if (d.st_ino==rino && d.st_dev==rdev)
			return(pname(str,name));
		file = open(dotdot,0);
		fstat(file, &dd);
		chdir(dotdot);
		if(d.st_dev == dd.st_dev) {
			if(d.st_ino == dd.st_ino)
				return(pname(str,name));
			do
				if (read(file, (char *)&dir, sizeof(dir)) < sizeof(dir)) {
					fprintf(stderr,"read error in ..\n");
					exit(1);
				}
			while (dir.d_ino != d.st_ino);
		}
		else do {
				if(read(file, (char *)&dir, sizeof(dir)) < sizeof(dir)) {
					fprintf(stderr,"read error in ..\n");
					exit(1);
				}
				stat(dir.d_name, &dd);
			} while(dd.st_ino != d.st_ino || dd.st_dev != d.st_dev);
		close(file);
		__cat(name,&dir,&off);
	}
}

__cat(name,dir,off)
char	*name;
struct direct	*dir;
int	*off;
{
	register i, j;

	i = -1;
	while (dir->d_name[++i] != 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];
}
