function [post,lik,lli] = hmeEval(hme,k,x,y)
% [] = hmeEval(hme,k,x,y)
%
% Evaluate the HME model given samples x and class labels y.
%
% INPUTS
%	hme	HME model
%	k	number of classes
%	x	dxn matrix of samples
%	[y]	kxn vector of class memberships
%
% OUTPUTS
%	post	kxn matrix of class posteriors
%	lik	1xn vector of sample likelihoods (if y is given)
%	lli	log likelihood (if y is given)
%
% Calls logistK_eval.
%
% David Martin <dmartin@eecs.berkeley.edu> 
% Charless Fowlkes <fowlkes@eecs.berkeley.edu>
% May 7, 2002

% Copyright (C) 2002 David R. Martin <dmartin@eecs.berkeley.edu>
% Copyright (C) 2002 Charless C. Fowlkes <fowlkes@eecs.berkeley.edu>
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation; either version 2 of the
% License, or (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA, or see http://www.gnu.org/copyleft/gpl.html.

error(nargchk(3,4,nargin));
if nargin > 3,
  error(nargoutchk(1,3,nargout));
else
  error(nargoutchk(1,1,nargout));
end

[d,n] = size(x);

if hme.leaf,

  % evaluate expert
  if nargin > 3,
    [post,lik,lli] = logistK_eval(hme.param,x,y);
  else
    post = logistK_eval(hme.param,x);
  end

else

  % evaluate gating function
  gate = logistK_eval(hme.param,x);

  % combine post,lik from children using gating function
  post = zeros(k,n);
  lik = zeros(1,n);
  for i = 1:length(hme.children),
    if nargin > 3,
      [post_i,lik_i] = hmeEval(hme.children{i},k,x,y);
      lik = lik + lik_i .* gate(i,:);
    else
      post_i = hmeEval(hme.children{i},k,x);
    end
    post = post + post_i .* repmat(gate(i,:),k,1);
  end

  % log-likelihood
  if nargin > 3,
    lli = sum(log(lik+eps));
  end
  
end

