function net = mixunpak(net, w)
%mixunpak Separates weight vector into weight and bias matrices for a mixture of experts model. 
%
%	NET = MIXUNPAK(NET, W) takes a mixtures of experts data structure
%	NET and  a weight vector W, and returns a network data structure 
%       identical to the input network, except that the weights and biases
%       of the expert networks and of the gating network (which are GLMs) 
%       have been set to the corresponding elements of W.
%
%       See also
%       glmunpak, mix, mixpak, mixfwd, mixerr, mixgrad
%       
%
%       Copyright: Perry Moerland

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

if ((strcmp(net.tag,'kernel') & ((net.nwts+net.gate.nparams) ~= length(w))) | (strcmp(net.tag,'standard') & (net.nwts ~= length(w))))
  error('Invalid weight vector length')
end

nin = net.nin;
nout = net.nout;
nexp = net.nexp;

index1 = 1;
for i=1:nexp
 index2 = (index1+net.exp(i).nwts)-1;
 net.exp(i) = glmunpak(net.exp(i),w(index1:index2));
 index1 = index2+1;
end;

% gating network is GLM
index2 = (index1+net.gate.nwts)-1;
net.gate = glmunpak(net.gate,w(index1:index2));
  
