function [varargout] = aamlib_parzenGaussianClassifier(varargin)
% function [varargout] = aamlib_parzenGaussianClassifier(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 = [];
h = 1;
% just to make sure that the covariance matrix is not singular
reg_const = 0.1;
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'groups'
            groups = varargin{i+1};
        case 'data'
            X = varargin{i+1};
        case 'h'
            h = 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 = cell(G,1);
for i=1:G
    B{i} = [groups(i).shapedata(:).b];
end
g = [];
for j=1:G
    g = cat(1, g, parzenGauss(X, B{j}, h));
end
[g, ind] = sort(g, 1, 'descend');
varargout{1} = ind;
varargout{2} = g;
return;
%%%
%
%%%
function P = parzenGauss(X, Xd, h)

M = size(X,2);
N = size(Xd,2);
P = zeros(1,M);
for i=1:M
    x = X(:,i);
    p = 0;
    for j = 1:N
        xn = Xd(:,j);
        p = p + isogauss(x-xn, 1);
    end
    P(i) = p/N;
end


return
%%%
%
%%%
function p = isogauss(x, h)
den = sqrt(2*pi*(h^2));
num = exp(-(x'*x)/(2*h^2));
p = num./den;
return