function [clusters, centers] = clusterPatches(numClusters, features, ...
  toCluster, numTries)
% Clusters the patches
%
% toCluster: indicator vector indicating what patches to cluster.
%
% Author: saurabh.me@gmail.com (Saurabh Singh).

if nargin < 4
%  numTries = 5;
  numTries = 1;
end

minSum = 0;
features = features(toCluster, :);
for i = 1 : numTries %1
  fprintf('About to run clustering\n');
  tic;
  [clIds, cents, err] = doFigTree(numClusters, features);
%   [clIds, cents, err] = doKMeansPlusPlus(numClusters, features);
  toc;
  sumErr = sum(err);
  fprintf('Error sum: %f\n', sumErr);
  if minSum < eps || sumErr < minSum
    minSum = sumErr;
    clustIds = clIds;
    centers = cents;
    fprintf('    selected');
  end
  fprintf('\n');
end
clusters = zeros(size(toCluster));
clusters(toCluster) = clustIds;
end

function [clustIds, centers, sumErr] = doKMeans(numClusters, features)
% Normal Kmeans
[clustIds, centers, sumErr] = kmeans(allFeatures, numClusters);
end

function [clustIds, centers, sumErr] = doKMeansPlusPlus(numClusters, ...
  features)
[clustIds, centers] = kmeanspp(features', numClusters);
clustIds = clustIds';
centers = centers';
sumErr = sum(errSum(features, centers, clustIds, numClusters));
end

function [clustIds, centers, sumErr] = doGaussMixModel(numClusters, ...
  features)
[mtrs, omtr] = GaussianMixture(features, numClusters + numClusters/4, ...
  numClusters , true);
prop = [omtr.cluster.pb];
mu = [omtr.cluster.mu]';
sigma = [omtr.cluster.R];
sigma = reshape(sigma, size(mu, 2), size(mu, 2), size(mu, 1));
distri = gmdistribution(mu, sigma, prop);
clustIds = cluster(distri, allFeatures);
centers = [];
% TODO: Fill in the 'centers'.
end

function [clustIds, centers, sumErr] = doFigTree(numClusters, features)
[kClust, rx, clustIds, centers, clustPts, clustR] = ...
  figtreeKCenterClustering(size(features, 2), size(features, 1), ...
    features', numClusters);
clustIds = clustIds' + 1;
centers = centers';
sumErr = sum(calcErrSum(features, centers, clustIds, numClusters));
end
