function [S,RANGE,SELECT] = myrf(THIS,TIME,FUNC,SELECT,OPT)
% MYRF  [Not a public function] Response function backend.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright 2007-2012 Jaromir Benes.

% Parse required input arguments.
IP = inputParser();
IP.addRequired('M',@(x) isa(THIS,'model'));
IP.addRequired('TIME',@isnumeric);
IP.parse(THIS,TIME);

% Tell whether time is nper or range.
if length(TIME) == 1 && round(TIME) == TIME && TIME > 0
    RANGE = 1 : TIME;
else
    RANGE = TIME(1) : TIME(end);
end
nper = length(RANGE);

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

ny = sum(THIS.nametype == 1);
nx = size(THIS.solution{1},1);
nalt = size(THIS.Assign,3);
nrun = length(SELECT);

% SIMULATE RESPONSE FUNCTION
% ===========================

% Output data from `timedom.srf` and `timedom.icrf` include the pre-sample
% period.
Phi = nan(ny+nx,nrun,nper+1,nalt);

[flag,index] = isnan(THIS,'solution');
for ialt = find(~index)
    [T,R,K,Z,H,D,U] = mysspace(THIS,ialt,false); %#ok<ASGLU>
    Phi(:,:,:,ialt) = FUNC(T,R,[],Z,H,[],U,[],ialt,nper);
end

% Report solutions not available.
if flag
    utils.warning('model', ...
        '#Solution_not_available', ...
        sprintf(' #%g',find(index)));
end

% CREATE OUTPUT DATA
% ===================

S = struct();

maxlag = -min(imag(THIS.solutionid{2}));

% Permute Phi so that Phi(k,t,m,n) is the response of the k-th variable to
% m-th init condition at time t in parameterisation n.
Phi = permute(Phi,[1,3,2,4]);

template = tseries();
comment = repmat(SELECT,[1,1,nalt]);

% Measurement variables.
Y = Phi(1:ny,:,:,:);
for i = find(THIS.nametype == 1)
    y = permute(Y(i,:,:,:),[2,3,4,1]);
    if OPT.delog && THIS.log(i)
        y = exp(y);
    end
    name = THIS.name{i};
    thiscomment = regexprep(comment,'.*',[name,' <- $0'],'once');
    S.(name) = replace(template,y,RANGE(1)-1,thiscomment);
end

% Transition variables.
X = myreshape(THIS,Phi(ny+1:end,:,:,:));
offset = sum(THIS.nametype == 1);
for i = find(THIS.nametype == 2)
    x = permute(X(i-offset,:,:,:),[2,3,4,1]);
    if OPT.delog && THIS.log(i)
        x = exp(x);
    end
    name = THIS.name{i};
    thiscomment = regexprep(comment,'.*',[name,' <- $0'],'once');
    S.(name) = replace(template,x,RANGE(1)-1-maxlag,thiscomment);
end

% Shocks.
e = zeros(nper,nrun,nalt);
for i = find(THIS.nametype == 3)
    name = THIS.name{i};    
    thiscomment = regexprep(comment,'.*',[name,' <- $0'],'once');
    S.(name) = replace(template,e,RANGE(1),thiscomment);
end

% Parameters.
for i = find(THIS.nametype == 4)
    S.(THIS.name{i}) = permute(THIS.Assign(1,i,:),[1,3,2]);
end

end