function [Y,W,E] = simulatemean(T,R,K,Z,H,D,~,A0,E,NPER,ANT,DEV,Q,q)
% simulatemean  [Not a public function] Simulate mean in general state space.
%
% Backend IRIS function.
% No help provided.

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

% TODO: Simplify treatment of ea and eu.

if ~exist('Q','var')
    Q = [];
end

if ~exist('q','var')
    q = [];
end

isnonlin = ~isempty(Q) && ~isempty(q);

if ANT
    anticipated = @real;
    unanticipated = @imag;
else
    anticipated = @imag;
    unanticipated = @real;
end    

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

ny = size(Z,1);
[nx,nb] = size(T);
nf = nx - nb;
ne = size(E,1);

Y = nan(ny,NPER);
W = nan(nx,NPER); % := [xf;a]
ea = anticipated(E);
eu = unanticipated(E);

lastea = max([0,find(any(ea ~= 0,1),1,'last')]);
lasteu = max([0,find(any(eu ~= 0,1),1,'last')]);
ia = any(abs(R(:,1:ne*lastea)) > 0,1);
iu = any(abs(R(:,1:ne)) > 0,1);

if isnonlin
    nn = size(q,1);
    lastn = max([0,find(any(q ~= 0,1),1,'last')]);
    in = any(abs(Q(:,1:nn*lastn)) > 0,1);
end

for t = 1 : NPER
    if t == 1
        W(:,t) = T*A0;
    else
        W(:,t) = T*W(nf+1:end,t-1);
    end
    if ~DEV
        W(:,t) = W(:,t) + K;
    end
    if lastea > 0 && any(ia)
        eat = ea(:,t:t+lastea-1);
        eat = eat(:);
        W(:,t) = W(:,t) + R(:,ia)*eat(ia);
        lastea = lastea - 1;
        ia = ia(1,1:end-ne);
    end
    if lasteu > 0 && any(iu)
        W(:,t) = W(:,t) + R(:,iu)*eu(iu,t);
        lasteu = lasteu - 1;
    end
    if isnonlin && lastn > 0 && any(in)
        qt = q(:,t:t+lastn-1);
        qt = qt(:);
        W(:,t) = W(:,t) + Q(:,in)*qt(in);
        lastn = lastn - 1;
        in = in(1,1:end-nn);
    end
end

% Mesurement variables.
if ny > 0
    Y = Z*W(nf+1:end,1:NPER) +...
        H*(eu(:,1:NPER) + ea(:,1:NPER));
    if ~DEV
        Y = Y + D(:,ones(1,NPER));
    end
end

end