
/*
 * csh - a shell by PJAC
 * dirs.c - directory stack handling
 */

#include "csh.h"

/*
 * push a directory onto the directory stack
 */
do_pushd(argc, argv)
char	**argv;
{
	char	*xp;

	if(argc > 2)
		syn_err();
	if(argc == 1){
		/* swap top of dirstack with CWD */
		if(!ndirstack){
			puterr("Directory stack empty.\n");
			return(ERR);
		}
		if(chdir(dirstack[ndirstack - 1]) < 0){
			inv_dir(dirstack[ndirstack-1]);
			return(ERR);
		}
		free(dirstack[ndirstack - 1]);
		dirstack[ndirstack - 1] = strsave(CWD);
		get_dir();
		return(OK);
	}
	/* push a new directory onto stack */
	if(ndirstack >= MAX_DSTACK - 1){
		puterr("Directory stack full.\n");
		return(ERR);
	}
	xp = strsave(CWD);
	if(chdir(argv[1]) < 0){
		inv_dir(argv[1]);
		free(xp);
		return(ERR);
	}
	get_dir();
	dirstack[ndirstack++] = xp;
	return(OK);
}

/*
 * pop the directory stack, ignore arguments
 */

do_popd(argc, argv)
char	**argv;
{
	if(!ndirstack){
		puterr("Directory stack empty.\n");
		return(ERR);
	}
	if(chdir(dirstack[ndirstack-1]) < 0){
		inv_dir(dirstack[ndirstack-1]);
		return(ERR);
	}
	ndirstack--;
	get_dir();
	return(OK);
}

inv_dir(str)
char	*str;
{
	puterr(str);
	puterr(" : Invalid directory.\n");
}

/*
 * print out directory stack
 */
do_dirs(argc, argv)
char	**argv;
{
	int	i;

	put_s(CWD);
	for(i = ndirstack - 1 ; i >= 0; i--){
		put_s(" ");
		put_s(dirstack[i]);
	}
	put_s("\n");
}
