function [X,Y,Xval,Yval] = collectPartitions(data,CV,oneTrialF,command)
%%% [X,Y,Xval,Yval] = collectTrainValidation(features,CV,oneTrialF,command)
%%%   train.features: ntasks x ntrials cell array of featurized data
%%%        .classes: ntasks x ntrials matrix of class labels
%%%   CV.classes: ntasks x ntrials matrix of class labels
%%%   CV.validateIndices: ntasks x ntrials cell array of validate sample indices
%%%   CV.parms.firstMode
%%%           .nModes
%%%  Returns
%%%   X: nfeatures x nSamples training data
%%%   Y: 1 x nSamples train class labels
%%%   Xval: nfeatures x nSamples validation data
%%%   Yval: 1 x nSamples validation class labels

[r,c] = size(data.features);
X = [];
Y = [];
Xval = [];
Yval = [];

if nargin > 3 && strcmp(command,'train')
  
  %% Collect train and validation data

  for ri = 1:r
    for ci = 1:c
      oneTrial = data.features{ri,ci};
      oneTrialClass = data.classes(ri,ci);
      trainIndices = 1:size(oneTrial,2);
      if ~isempty(CV.validateIndices)
	trainIndices = setdiff(trainIndices,CV.validateIndices{ri,ci});
      end

      [X1,Y1] = oneTrialF(oneTrial,trainIndices,oneTrialClass,CV);
      X = [X X1];
      Y = [Y Y1];

      if ~isempty(CV.validateIndices)
	[Xval1,Yval1] = oneTrialF(oneTrial,CV.validateIndices{ri,ci},oneTrialClass,CV);
	Xval = [Xval Xval1];
	Yval = [Yval Yval1];
      end
    end
  end

else
  %% collect test data
  
  for ri = 1:r
    for ci = 1:c
      oneTrial = data.features{ri,ci};
      oneTrialClass = data.classes(ri,ci);
      [X1,Y1] = oneTrialF(oneTrial,1:size(oneTrial,2),oneTrialClass,CV);
      X = [X X1];
      Y = [Y Y1];
    end
  end
end

