## Copyright (C) 2016 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 {} {} import (@var{pkg}, @dots{})
## @deftypefnx {} {@var{L} =} import (@var{pkg}, @dots{})
## @deftypefnx {} {@var{L} =} import
## Import packages by adding them to the function search path.
##
## If an output argument is specified, the import list is returned as a
## cell array of strings @var{L}.
##
## @end deftypefn

## Author: jwe


function L = import (varargin)

  persistent import_list;
  if (isempty (import_list))
    import_list = {};
  end

  P = strsplit (path (), pathsep);

  for i=1:numel (varargin)
  
    if (ismember (varargin{i}, import_list))
      continue;
    endif
    
    S = strsplit (varargin{i}, '.');
    if (strcmp (S{1}, 'matlab'))
      S(1) = []; % or replace with 'octave'
    endif
    S(end) = []; % is '*', or function, or class name
    
    D = __find_dir__ (S, P);
    
    if (isempty (D))
      error ("Import '%s' failed.", varargin{i});
    else
      import_list{end+1} = varargin{i};
      for j=1:numel (D)
        addpath (D{j});
      endfor
    endif
    
  endfor

  if (nargin == 0 || nargout > 0)
    L = import_list;
  endif

endfunction


function D = __find_dir__ (S, P)

  D = {};
  s = '';
  for i=1:numel(S)
    s = [s filesep '+' S{i}];
  endfor
  for i=1:numel (P)
    p = fullfile (P{i}, s);
    if (exist (p, 'dir'))
      D{end+1} = p;
    endif
  endfor
  
endfunction
