function [pick, rest] = cut(d,n)
%CUT Cut the dataset into n pieces for x validation
%    purposes
%    
%    The cutting process respects the classes repartition.
%    
%    [PICK, REST] = CUT (D,N) cuts D in N sub-dataset, each of
%    which is placed in one cell of the cell array PICK. For
%    each <code>pick{j}</code>, the rest of the data set is
%    placed inside <code>rest{j}</code>
%    
%    See also: XVAL
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose	Cut the dataset into n pieces for x validation purposes.
%	The cutting process respects the classes repartition.
%
%   @synopsis	[pick, rest] = cut (d,n)
%   @description  cuts <code>d</code> in <code>n</code> sub-dataset, each of which is
%	placed in one cell of the cell array <code>pick</code>. For each <code>pick{j}</code>, the
%	rest of the data set is placed inside <code>rest{j}</code>
%
%   @see xval
%
%MAN_PAGE_END

loadfromdisk(d)

classeslist = get(d,'classeslist');

ns = get(d,'ns');
nc = get(d,'nc');

pick = cell(n,1);
rest = cell(n,1);

for j=1:n,
	pick{j} = dataset;
	rest{j} = dataset;
end

for i=1:nc,
	sub = classpart(d,classeslist(i));
	subns = get(sub,'ns');
	slices = floor(subns / n) * ones (n,1);
	lim = mod(subns,n);
	slices(1:lim) = slices(1:lim) + 1;
	start = 1;
	rp = randperm (subns);
	slices = slices(randperm(length(slices)));
	for j=1:n,
		select = rp(start:start+slices(j)-1);
		rr = struct('type','()');
		rr.subs = {select,':'};
		tpick = subsref(sub,rr);
		rr = struct('type','()');
		rr.subs = {setdiff(1:subns,select),':'};
		trest = subsref(sub,rr);
		pick{j} = [pick{j};tpick];
		rest{j} = [rest{j};trest];
		start=start+slices(j);
	end
end
