
#include <string.h>

#include "rc.h"

/* traverse $cdpath if the directory given is not an absolute pathname */

void
b_cd ( char ** av ) {
	List *s, nil;
	char *path = NULL;
	size_t t, pathlen = 0;

	if (*++av == NULL) {
		s = varlookup("home");
		*av = (s == NULL) ? "/" : s->w;
	} else if (av[1] != NULL) {
		arg_count("cd");
		return;
	}

	if ( isabsolute(*av) ) { /* absolute pathname? */
		if (chdir(*av) < 0) {
			set(FALSE);
			if (!cd_from_exec) uerror(*av);
		} else set(TRUE);
	} else {
		s = varlookup("cdpath");
		if (s == NULL) {
			s = &nil;
			nil.w = "";
			nil.n = NULL;
		}
		do {
			if (s != &nil && *s->w != '\0') {
				t = strlen(*av) + strlen(s->w) + 2;
				if (t > pathlen)
					path = nalloc(pathlen = t);
				strcpy(path, s->w);
				if (!streq(s->w, "/")) /* "//" is special to POSIX */
					strcat(path, "/");
				strcat(path, *av);
			} else {
				pathlen = 0;
				path = *av;
			}
			if (chdir(path) >= 0) {
				set(TRUE);
/* MAD changed:
the following printf commented - cos it looks silly
				if (interactive && *s->w != '\0' && !streq(s->w, "."))
					fprint(1, "%s\n", path);
*/
				return;
			}
			s = s->n;
		} while (s != NULL);
		if (!cd_from_exec) fprint(2, "couldn't cd to %s\n", *av);
		set(FALSE);
	}
}
