function p = genpath(d,traverseMatlabToolbox)
%GENPATH Generate reasonable path based on toolbox.
%   P = GENPATH  returns a new path string by adding
%   all the directories below MATLABROOT/toolbox.
%
%   P = GENPATH(DIR) returns a path string formed by 
%   recursively adding all the directories below DIR.

%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.4 $ $Date: 1997/11/21 23:31:50 $

if nargin==0,
  p = genpath(fullfile(matlabroot,'toolbox','matlab'),1);
  p = [p genpath(fullfile(matlabroot,'toolbox'),0)];
  if length(p) > 1, p(end) = []; end % Remove trailing pathsep
  return
end

p = '';

if ~traverseMatlabToolbox & strcmp(d,fullfile(matlabroot,'toolbox','matlab'))
  return
end

files = dir(d);
if isempty(files)
  return
end

%
% Add d to the path if it contains any non-directories
%
isdir = logical(cat(1,files.isdir));
if ~all(isdir)
  p = [p d pathsep];
end

%
% Recursively descend through directories which are neither
% private nor "class" directories.
%
if isvms
  methodsep = '$';
else
  methodsep = '@';
end

dirs = files(isdir);
for i=1:length(dirs)
  dirname = dirs(i).name;
  if ~strcmp( dirname,'.')         &...
     ~strcmp( dirname,'..')        &...
     ~strncmp(dirname,methodsep,1) &...
     ~strcmp( dirname,'private') 

   p = [p genpath(fullfile(d,dirname),0)];
  end
end
