## Copyright (C) 2009-2011 John W. Eaton
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn {Command} {} which name @dots{}
## Display the type of each @var{name}.  If @var{name} is defined from a
## function file, the full name of the file is also displayed.
## @seealso{help, lookfor}
## @end deftypefn

function varargout = which (varargin)

  if (nargin > 0 && iscellstr (varargin))
    isall = strcmpi (varargin,'-all');
    varargin = varargin(~isall);
    for i = 1:numel(varargin)
      if any(isall)
        pth = path;
        do
          m = __which__ (varargin{i});
          if (nargout == 0)
            which_disp (m);
          else
            varargout{1}{end+1} = m.file;
          endif
          % FIXME % rmpath cannot remove current path so give up
          if any(strcmp({'.',pwd},fileparts(m.file))), break; end
          rmpath(fileparts(m.file));
        until isempty(m.file) && isempty(m.type)
        path(pth);
      else
        m = __which__ (varargin{i});
        if (nargout == 0)
          which_disp (m);
        else
          varargout{1}{end+1} = m.file;
        endif
      endif
    endfor
    if (nargout != 0)
      varargout{1} = varargout{1}(~cellfun(@isempty,varargout{1}));
    endif
  else
    print_usage ();
  endif

endfunction

function which_disp (m)

  if (isempty (m.file))
    if (! isempty (m.type))
      printf ("`%s' is a %s\n",
              m.name, m.type);
    endif
  else
    if (isempty (m.type))
      printf ("`%s' is the file %s\n",
              m.name, m.file);
    else
      printf ("`%s' is a %s from the file %s\n",
              m.name, m.type, m.file);
    endif
  endif
    
endfunction
