function libs = get_libraries(user,varargin)

% get_libraries - get and select libraries from user
% --------------------------------------------------
%
% libs = get_libraries(user)
%      = get_libraries(user,'field',value, ...)
%
% Input:
% ------
%  user - input user (def: active user)
%  field - library field name
%  value - library field value
%
% Output:
% -------
%  libs - selected libraries

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 4335 $
% $Date: 2006-03-21 12:12:34 -0500 (Tue, 21 Mar 2006) $
%--------------------------------

%------------------------------------
% HANDLE INPUT
%------------------------------------

%--
% set default active user
%--

if (nargin < 1 || isempty(user))
	user = get_active_user;
end

% NOTE: return quickly on empty user

if (isempty(user))
	libs = []; return;
end

%------------------------------------
% GET USER LIBRRARIES
%------------------------------------

%--
% get libraries paths from user
%--

path = user.library;

% NOTE: return quickly on no library paths

if (isempty(path))
	libs = []; return;
end

%--
% get libraries from paths
%--

libs = empty(library_create);

for k = numel(path):-1:1
	
	if (~exist_dir(path{k}))
				
		%-- 
		% ask whether to unsubscribe or locate
		%--

		[user, lib] = library_relocate(user, path{k}, [], 1);
	
	else

		[root,name] = path_parts(path{k}); file = get_library_file(root,name); 
		
		lib = load_library(file);
		
	end
	
	if (isempty(lib))
		continue;
	end	

	libs(end + 1) = lib;	
	
end

%--
% return if there are no selection criteria
%--

if (isempty(varargin))
	return;
end

%---------------------------------------------------------------
% SELECT FROM AVAILABLE LIBRARIES
%---------------------------------------------------------------

%--
% extract selection field value pairs
%--

[field,value] = get_field_value(varargin);

%--
% loop over selection fields
%--

for j = 1:length(field)
	
	%--
	% use field if it is in fact a library field
	%--
	
	if (isfield(libs(1),field{j}))
		
		%--
		% check library fields for value match
		%--
		
		for k = length(libs):-1:1
			
			if (~isequal(libs(k).(field{j}),value{j}))
				libs(k) = [];
			end
			
		end
		
	end
end