function [FILESANDDIRS, FILES, DIRS] = filemenu(DNAME, IMEXTS)
% [FILESANDDIRS, FILES, DIRS] = filemenu(DNAME, IMEXTS)
% 
% Create cell arrays of image files and directories beneath current directory.
% Image files are files that end in 'mr', or in anything understood by imread.
%
% DIRS is a list of directories; FILES is a list of image files only.
% FILESANDDIRS contains both.
%
% IMEXTS is a cell array of the allowable file extensions.  The default is
%  IMEXTS = { 'mr' 'tif' 'tiff' 'jpg' 'jpeg' 'pcx' 'hdf' 'xwd' 'bmp' };
%

% First, get a complete directory listing
D = dir(DNAME);

% Initialize DIRS and FILES
DIRS = [];
FILES = [];

% If the directory was not found, return empty cell arrays
if length(D)==0, 
  disp(sprintf('filemenu: Unable to read from directory %s\n', DNAME)),
  FILESANDDIRS = { };
  return;
end;

% If directory was found, the first two entries are always current directory and '..'
DIRS = strvcat(DNAME, '..');

% If no IMEXTS were specified, set the default
if nargin<2,
  IMEXTS = { 'mr' 'tif' 'tiff' 'jpg' 'jpeg' 'pcx' 'hdf' 'xwd' 'bmp' };
else
  IMEXTS = cellstr(lower(char(IMEXTS)));
end;

for i=1:length(D),
  if strcmp(D(i).name, '..') | strcmp(D(i).name, '.'),
    % Skip '.' and '..', since they've already been accounted for
    
  elseif D(i).isdir,
    % If this one's a directory, add it to the  list
    DIRS = strvcat(DIRS, D(i).name);
  
  else,
    % Otherwise, look for image file endings
    ni = lower(D(i).name);
    ext = fliplr(strtok(fliplr(ni), '.'));
    if strmatch(ext, IMEXTS, 'exact'),
       % The fliplr makes sure that any spaces are added at beginning of name
       FILES = strvcat(FILES, fliplr(D(i).name));
   end;
  end; 
end;
FILES = fliplr(FILES);
   
% Sort the file names, and all DIR names after the first two
if size(FILES,1)>1,
   FILES = sortrows(FILES);
end
if isempty(FILES), 
   FILES={};
else
   FILES = cellstr(fliplr(FILES)); 
end
for i=1:length(FILES),
   FILES{i} = fliplr(FILES{i});
end


if size(DIRS,1)>3,
  DIRS(3:size(DIRS,1),:) = sortrows(DIRS(3:size(DIRS,1),:));
end;
if isempty(DIRS), 
   DIRS={};
else
   DIRS = cellstr(DIRS); 
end

FILESANDDIRS = { DIRS{:} FILES{:} };

