function [varargout] = aamlib_knnClassifier(varargin)
% function [varargout] = aamlib_knnClassifier(varargin)
%
% Dr. A. I. Hanna (2007)

if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(['Arguments to ', mfilename,' must come param/value in pairs.'])
end
groups = [];
X = [];
K = [];
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'groups'
            groups = varargin{i+1};
        case 'data'
            X = varargin{i+1};
        case 'k'
            K = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to ', mfilename, '.  Name was ' varargin{i}])
    end
end
if isempty(groups)
    error('Parameter groups must be supplied');
end
if isempty(X)
    error('Parameter X must be supplied');
end
N = size(X,2);

G = length(groups);
B = [];
N = [];
minx = realmax;
for i=1:G
    b = [groups(i).shapedata(:).b];
    sz = size(b);
    B = cat(2, B, b);
    N = cat(1, N, i*ones(sz(2),1));
    if sz(2)<minx
        minx = sz(2);
    end
end
if isempty(K)
    K = minx;
end
if K>minx
    K = minx;
end
g = [];
p = knn(X, B, N, K);
[g, ind] = sort(p, 1, 'descend');
varargout{1} = ind;
varargout{2} = g;
varargout{3} = K;
return;
%%%
%
%%%
function P = knn(X, Xd, labels, K)
M = size(X,2);
N = size(Xd,2);
num_groups = max(labels);
P = zeros(num_groups,M);
for i=1:M
    x = X(:,i);
    d = sqrt(sum((Xd - x*ones(1, N)).^2,1));
    [d, ind] = sort(d, 'ascend');
    L = labels(ind(1:K));
    for k=1:num_groups
        Kk = sum(L==k);
        P(k, i) = Kk/K;
    end
end
return
