function user = user_subscribe(lib,user)

% user_subscribe - subscribe user to library
% ------------------------------------------
%
% user = user_subscribe(lib,user)
%
% Input:
% ------
%  lib - library to subscribe to
%  user - user to subscribe (def: active user)
%
% Output:
% -------
%  user - updated user

%--------------------------------
% Author: Harold Figueroa
%--------------------------------
% $Revision: 1632 $
% $Date: 2005-08-23 13:09:06 -0400 (Tue, 23 Aug 2005) $
%--------------------------------

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

% TODO: allow using library name

%--
% get active user as default
%--

% NOTE: also compute active user flag to determine whether to update active user

if (nargin < 2)
	user = get_active_user; 
	active = 1;
else
	temp = get_active_user;
	active = strcmp(temp.name, user.name);
end

%-------------------------------
% SUBSCRIBE TO LIBRARY
%-------------------------------

%--
% subscribe user to library if needed
%--

if (isempty(user.library))

	user.library{end + 1} = lib.path; 
	
	user.default = 1; user.active = 1;

else
	
	% NOTE: return if we are already subscribed to this library
	
	if (~isempty(get_libraries(user,'path',lib.path)))
		return;
	end
	
	%--
	% update library structures to match user libraries
	%--
	
	% NOTE: this is a hack, put this in a catch to handle older libraries
	
	existing = get_libraries(user);
	
	lib = struct_update(existing(end),lib);
	
	%--
	% add library to subscriptions
	%--
	
	user.library{end + 1} = lib.path;
			
end

%--
% add user to library
%--

if ~any(strcmp(lib.user, user.name))
	lib.user{end + 1} = user.name;
end

%--
% save user and possibly update active user
%--

user_save(user);

if (active)
	set_active_user(user);
end

library_save(lib);

%--
% create shortcut to libraries not in libraries directory
%--

libs_path = [user_root(user), filesep, 'Libraries'];

if (~strncmp(libs_path,lib.path,length(libs_path)))
	
	create_shortcut( ...
		lib.path, libs_path, lib.name ...
	);

end
	
	
	
	