function THIS = refresh(THIS,IALT)
% refresh  Refresh dynamic links.
%
% Syntax
% =======
%
%     M = refresh(M)
%
% Input arguments
% ================
%
% * `M` [ model ] - Model object whose dynamic links will be refreshed.
%
% Output arguments
% =================
%
% * `M` [ model ] - Model object with dynamic links refreshed.
%
% Description
% ============
%
% Example
% ========
%
%     m = refresh(m);
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if isempty(THIS.Refresh)
   return
end

nalt = size(THIS.Assign,3);
try
    IALT; %#ok<VUNUS>
catch %#ok<CTCH>
    IALT = 1 : nalt;
end

%**************************************************************************

% We cannot use cellfun to evaluate the equations because dynamic links can
% be recursive.

eqtn = THIS.eqtnF(THIS.eqtntype == 4);
n = size(THIS.Assign,2);
x = [THIS.Assign(1,:,IALT),THIS.stdcorr(1,:,IALT)];
x = permute(x,[3,2,1]);
for j = 1 : length(THIS.Refresh)
   namepos = THIS.Refresh(j);
   x(:,namepos) = feval(eqtn{j},x,1);
end
x = ipermute(x,[3,2,1]);
THIS.Assign(1,:,IALT) = x(1,1:n,:);
THIS.stdcorr(1,:,IALT) = x(1,n+1:end,:);

end