function d = join(d1,d2)
%JOIN joins two data sets
%    
%    D = JOIN(D1,D2) Joins two different data sets D1 and D2,
%    even if they are not compatible (they do not share the
%    same variables). This can lead to a strongly sparse data
%    set if the data sets are fairly different. Note also that
%    the variables will be resorted during the process.
%    
%    See also: VERTCAT
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose	joins two data sets
%
%   @synopsis	d = join(d1,d2)
%   @description  Joins two different data sets <code>d1</code> and <code>d2</code>, even if they are not compatible
%	(they do not share the same variables). This can lead to a strongly sparse data set if the data sets are fairly
%	different. Note also that the variables will be resorted during the process.
%
%   @see vertcat
%
%MAN_PAGE_END

loadfromdisk(d1)
loadfromdisk(d2)

f1 = d1.variables;
f2 = d2.variables;

nf = union(f1,f2);
nd1 = dataset;
nd2 = dataset;

tref=struct('type','()');
tref.subs = {':' 0};

for i=1:size(nf,1);
	find1 = find(strcmp(nf{i},f1));
	find2 = find(strcmp(nf{i},f2));
	if ~isempty(find1);
		tref.subs{2} = find1;
		nd1 = [nd1 subsref(d1,tref)];
	else
		nd1 = [nd1 dataset(nan+zeros(size(d1,1),1),'symbols',d2.symbols(find2),...
			'vartypes',d2.vartypes(find2),'labels',d1.labels,'variables',nf(i))];
	end
	if ~isempty(find2);
		tref.subs{2} = find2;
		nd2 = [nd2 subsref(d2,tref)];
	else
		nd2 = [nd2 dataset(nan+zeros(size(d2,1),1),'symbols',d1.symbols(find1),...
			'vartypes',d1.vartypes(find1),'labels',d2.labels,'variables',nf(i))];
	end
end

d = vertcat(nd1,nd2);
