function pushd(directory)

% PUSHD		push a directory onto the direcory stack
%   PUSHD dir-spec  adds dir-spec directory to the top of the directory
%      stack (making it the current working directory).
%   PUSHD  (with no arguments) swaps the top two elements on the directory
%      stack.
%   Use the functional form of PUSHD, such as PUSHD('dir-spec'), when the
%   directory specification is stored in a string.

global directory_stack
if isempty(directory_stack),  directory_stack = {};  end

if nargin > 0,
  %%% args: add directories to stack.

  % get cwd, chdir, push old cwd.  (that way we don't push if chdir bombs!)
  current = cd;
  cd(directory);
  directory_stack = {current directory_stack{:}};
else
  %%% no args: swap directories.

  if isempty(directory_stack),  error('No other directory.');  end

  % get cwd, pop top of stack and chdir, push cwd. (lossage = pop but no push)
  current = cd;
  new = directory_stack{1};
  directory_stack = directory_stack(2:length(directory_stack));
  cd(new);
  directory_stack = {current directory_stack{:}};
end

disp(cd);
for d = 1:length(directory_stack),
  disp(directory_stack{d});
end
