% disposables - Manage resources that need to be disposed of cleanly
%
% This is implemented as a message handler to be used as follows:
%
% >> ref=disposables('reg',x)  % register x as a disposable returning reference ref
% >> disposables('dereg',ref)  % deregister (but do not dispose) of registered object
% >> dx=disposables('get')     % get cell array of all registered objects
% >> disposables('dispose')    % dispose of and deregister all disposables
%
% In most cases, you will not need to use this function as resources should
% be disposed of correctly by the functions that acquire them. However, if
% things go wrong or the user presses Ctrl-C, some objects might not be
% disposed of properly and cause problems later. In this case, a call to
% disposables('dispose') should take care of it.

function varargout=disposables(msg,varargin)
	persistent registry

	switch(msg)
		case 'reg', 
			obj=varargin{1};
			registry = [registry, obj]; 
			varargout{1}=obj;
		case 'dereg', 
			obj=varargin{1};
			if ~isempty(registry)
				idx=find(registry==obj);
				registry=registry([1:idx-1,idx+1:length(registry)]);
			end
		case 'get'
			varargout{1}=registry;
		case 'dispose'
			for i=1:length(registry)
				registry(i).dispose();
			end
			registry=[];
	end
end

