function [randomized_targets,permutation]=cosmo_randomize_targets(ds,varargin)
% provides randomized target labels
%
% randomized_targets=cosmo_randmize_targets(ds[,'seed',seed)
%
% Inputs:
% ds dataset struct with fields .sa.targets and
% .sa.chunks
% 'seed', seed (optional) if provided, use this seed value for
% pseudo-random number generation
%
%
% Outputs:
% randomized_targets P x 1 with randomized targets
% If ds defines a repeated-measures design (which
% requires that each chunk has the same set of
% unique targets), then targets are randomized
% separately for each chunk.
% Otherwise (when each chunk is associated with
% exactly one sample, i.e. all samples are
% independent), the targets are randomized
% without considering the chunk values.
% permutation P x 1 with indices of permutation. It holds that
% randomized_targets == ds.sa.targets(permutation).
%
% Example:
% % generate tiny dataset with 15 chunks, each with two targets
% ds=cosmo_synthetic_dataset('nchunks',15);
% % show number of samples with targets 1 or 2
% histc(ds.sa.targets',1:2)
% %|| [15 15]
% % generate randomized targets
% rand_targets=cosmo_randomize_targets(ds);
% % the number of samples with targets 1 or 2 is the same ...
% histc(rand_targets',1:2)
% %|| [15 15]
% % ... but the targets are re-ordered
% all(ds.sa.targets==rand_targets)
% %|| false
% %
% % when using the 'seed' option, the output is deterministic
% % (multiple calls to this function always give the same output)
% rand_targets_deterministic=cosmo_randomize_targets(ds,'seed',314);
% rand_targets_deterministic'
% %|| [ 2 1 1 2 2 1 2 1 2 1 2 1 1 2 2 1 1 2 2 1 1 2 2 1 2 1 2 1 2 1 ]
%
% # For CoSMoMVPA's copyright information and license terms, #
% # see the COPYING file distributed with CoSMoMVPA. #