function [e] = mixmlperr_gate(net, x, t, post)
%mixmlperr_gate  Evaluate error function for the gating network in the gated experts model trained by EM.
%
%       E = MIXMLPERR_GATE(NET, X, T, POST) takes a gating network data
%       structure NET (which is a MLP) together with a matrix X of input 
%       vectors and a matrix T of target vectors, the posterior
%       probabilities POST, and evaluates the error function with respect 
%       to the network weights. The error function is the gating network's
%       contribution to the EM error fucntion.
%
%       See also
%       mixerr_em, mixmlp, mixmlpem, mixopt, mlpfwd
%
%       Copyright: Perry Moerland

% Check arguments for consistency
errstring = consist(net, 'mlp', x, post);
if ~isempty(errstring);
  error(errstring);
end

[y,z,a] = mlpfwd(net, x);

nout = size(a,2);
% Ensure that sum(exp(a), 2) does not overflow
maxcut = log(realmax) - log(nout);
% Ensure that exp(a) > 0
mincut = log(realmin);
a = min(a, maxcut);
a = max(a, mincut);
temp = exp(a);
y = temp./(sum(temp, 2)*ones(1,nout));
% Ensure that log(y) is computable
y(y<realmin) = realmin;
e = - sum(sum(post.*log(y)));


