function multiPlotParms(CV,otherfields,x,multicurve,multiplot)
% multiPlotParms(CV.msf,otherfields,names,x,multicurve,multiplot)
% multiPlotParms(CV.msf,...
%    {'TestTrial',5,'winSize',125,'winShift',32,'meanSubtract',1},'firstMode','nModes','nlags');

names = {CV.cvresultsNames{:} 'Val RMSE'};
nreps = CV.validate.repetitions;
resultsmat = CV.cvresults(:,1:end-nreps);
z=CV.cvresults(:,end-nreps+1:end);
resultsmat = [resultsmat mean(CV.cvresults(:,end-nreps+1:end),2)];

submat = resultsmat;
%%% select rows containing other field values
for i = 1:2:length(otherfields)
  f = char(otherfields{i});
  v = otherfields{i+1};
  c = whichColumn(names,f);
  submat = submat(submat(:,c)==v,:);
end

if nargin == 5
  multiplotcol = whichColumn(names,multiplot);
  multiplotvalues = unique(submat(:,multiplotcol));
  nplots = length(multiplotvalues)
  sqrtnplots = ceil(sqrt(nplots));
else
  sqrtnplots = 1;
  nplots = 1;
end
  
if nargin > 3
  multicurvecol = whichColumn(names,multicurve);
else
  multicurvecol = 0;
end

xcol = whichColumn(names,x);

for ip=1:nplots
  subplot(sqrtnplots,sqrtnplots,ip);
  
  if nplots > 1
    oneplotmat = submat(submat(:,multiplotcol)==multiplotvalues(ip),:);
  else
    oneplotmat = submat;
  end
  
  if multicurvecol > 0
    multicurvevalues = unique(oneplotmat(:,multicurvecol));
    ncurves = length(multicurvevalues);
  else
    ncurves = 1;
  end
  data = {};
  lastxvalues = [];
  legendText = {};
  for ic = 1:ncurves
    if multicurvecol > 0
      onecurve = oneplotmat(oneplotmat(:,multicurvecol) == ...
	  multicurvevalues(ic),:);
    else
      onecurve = oneplotmat;
    end
    xvalues = unique(onecurve(:,xcol));
    if ~isempty(lastxvalues) && ~all(xvalues == lastxvalues)
      error('multiPlotParms: x values not same in multiple curves');
    end
    [junk,indices] = sort(onecurve(:,xcol));
    onecurve = onecurve(indices,:);
    data = {data{:} onecurve(:,[xcol end])};
    if multicurvecol > 0
      legendText = {legendText{:} [num2str(multicurvevalues(ic)) ' ' ...
	    multicurve]};
    end
  end
  
  xs = [];
  for i = 1:length(data)
    plot(data{i}(:,1),data{i}(:,2));
    xs = [xs; data{i}(:,1)];
    hold on;
  end
  hold off;
  xlabel(x);
  %legend(legendText);
  if nplots > 1
    title([multiplot ' ' num2str(multiplotvalues(ip))]);
  end

end




function col = whichColumn(names,field)
col = 0;
for i=1:length(names)
  if strcmp(names{i},field)
    col = i;
  end
end

