function f = fullfile(varargin)
%FULLFILE Build full filename from parts.
%   FULLFILE(D1,D2, ... ,FILE) builds a full file name from the
%   directories D1,D2, etc and filename FILE specified.  This is
%   conceptually equivalent to
%
%      F = [D1 filesep D2 filesep ... filesep FILE] 
%
%   except that care is taken to handle the cases where the directory
%   parts D1, D2, etc. may begin or end in a filesep. Specify FILE = ''
%   to build a pathname from parts.  On VMS, care is taken to handle
%   the cases involving '[' or ']' too.
%
%   Examples
%     To build platform dependent paths to files:
%        fullfile(matlabroot,'toolbox','matlab','general','Contents.m')
%
%     To build platform dependent paths to a directory:
%        addpath(fullfile(matlabroot,'toolbox','matlab',''))
%
%   See also FILESEP, PATHSEP, FILEPARTS.

%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.12 $ $Date: 1997/11/21 23:35:22 $

if nargin<2, error('Not enough input arguments.'); end
fs = filesep;
f = varargin{1};

if ~isvms,
  for i=2:nargin,
    part = varargin{i};
    if isempty(f) | isempty(part)
      f = [f part];
    else
      % Handle the three possible cases
      if (f(end)==fs) & (part(1)==fs),
        f = [f part(2:end)];
      elseif (f(end)==fs) | (part(1)==fs)
        f = [f part];
      else
        f = [f fs part];
      end
    end
  end
  % Make sure a directory path ends in a fs on a MAC
  if strncmp(computer,'MAC',3) & isempty(varargin{end}) & f(end)~=fs
    f = [f fs];
  end
else % VMS
  %
  % decompose first element 
  %
  [lpath,name,ext] = fileparts(f);
  
  %
  % If a name exists, and is a valid directory specification
  % (ext is empty or ext is 'dir') then recompose f as a directory
  % specification.
  %
  if ~isempty(name),
    if isempty(ext) | strcmp(upper(ext),'.DIR'),
      f = [lpath(1:end-1) '.' name ']'];
    end;
  end;
  
  
  % Check for drive name by looking for a colon.  If none found,
  % assume this is the beginning of a partial path name.
  if isempty(f) | all(f ~= ':'),
    f = ['[.' f];
  elseif f(end)==':' & nargin>2,
    f = [f '['];
  end
  if f(end)==']', f(end) = []; end

  %
  % Append directory parts
  %
  for i=2:nargin,
    % Strip all fileseps and brackets from the parts.  Makes
    % the concatenation code below much simpler.
    part = varargin{i};
    if ~isempty(part) & part(1)=='[', part(1) = []; end
    if ~isempty(part) & part(1)==fs, part(1) = []; end
    if ~isempty(part) & part(end)==']', part(end) = []; end
    if ~isempty(part) & part(end)==fs, part(end) = []; end
    if i==nargin & ~isempty(part) & part(1)==']', part(1) = []; end

    if (i==nargin) & (f(end)~=':'), f = [f ']']; end % Add trailing bracket for filename

    if ~isempty(part)
      % Handle the possible cases
      if (f(end)==fs) | (f(end)=='[') | (f(end)==']') | (f(end)==':')
        f = [f part];
      else
        f = [f fs part];
      end
    end
  end
  f = lower(f);
end

