% INSTALLEXTENSIONSFORDIR installs the toolbox extensions found under the
% given directory.
% 
% CALL: utils.helper.installExtensionsForDir(dir)
% 
% M Hewitson 29-10-10
% 
% $Id: installExtensionsForDir.m,v 1.8 2011/03/25 15:14:42 mauro Exp $
% 
function res = installExtensionsForDir(varargin)

  extdir = varargin{1};
  
  if ~ischar(extdir)
    error('input a path to a directory of LTPDA extensions');
  end
  
  fprintf('* installing extensions under %s ...\n', extdir);
  
  % toolbox path
  aopath = fileparts(which('ao'));
  parts = regexp(aopath, '@', 'split');
  classpath = parts{1};
  
  % for each user class, look for a corresponding directory and copy any
  % extension methods in.
  % copy <module>/classes/<user_class>/<methods> to the toolbox
  userclasses = utils.helper.ltpda_userclasses;
  installedClassMethods = false;
  for ucl = userclasses
    extsdir = fullfile(extdir, 'classes', ucl{1});
    if exist(extsdir, 'dir')==7 
      fprintf('  * installing extensions for class %s ...\n', ucl{1});
      files = utils.prog.filescan(extsdir, '.m');
      dstdir = fullfile(classpath, ['@' ucl{1}]);
      for kk = 1:numel(files)
        f = files{kk};
        [path,name,ext] = fileparts(f);
        fprintf('      installing %s -> %s\n', name, ucl{1});
        [success, message, messageid] = copyfile(f, dstdir);
        if ~success
          fprintf(stderr, 'Failed to copy file %s to %s : %s', f, dstdir, message);
        else
          installedClassMethods = true;
        end
      end
    end
  end
  
  % Add subdirs to the MATLAB path
  addpath(extdir);
  % In order to include user-defined classes, we just need to add the <module>/classes folder
  addpath(fullfile(extdir, 'classes'));
  % In order to include user-defined models, we need to add the <module>/models folder and subfolders
  addpath(genpath(fullfile(extdir, 'models')));
  % In order to include user-defined functions, we need to add the <module>/functions folder and subfolders
  addpath(genpath(fullfile(extdir, 'functions')));
  % In order to include user-defined tests, we need to add the <module>/tests folder and subfolders
  addpath(genpath(fullfile(extdir, 'tests')));
  
  % It might be useful to remove the 'CVS' and '.svn' folders, if any
  utils.helper.remove_cvs_from_matlabpath();
  utils.helper.remove_svn_from_matlabpath();
  
  res = installedClassMethods;
  
  if installedClassMethods
    fprintf('----------------------------------------------------------------\n');
    fprintf('   Additional class methods were installed. These will be  \n');
    fprintf('   available next time you run ''clear all'' or ''clear classes''.\n');
    fprintf('----------------------------------------------------------------\n');
  end

  
end


