function [S,RANGE,SELECT,index] = srf(THIS,TIME,varargin)
% srf  Shock response functions.
%
% Syntax
% =======
%
%     S = srf(M,NPER,...)
%     S = srf(M,RANGE,...)
%
% Input arguments
% ================
%
% * `M` [ model ] - Model object whose shock responses will be simulated.
%
% * `RANGE` [ numeric ] - Simulation date range with the first date being
% the shock date.
%
% * `NPER` [ numeric ] - Number of simulation periods.
%
% Output arguments
% =================
%
% * `S` [ struct ] - Database with shock response time series.
%
% Options
% ========
%
% * `'delog='` [ *`true`* | `false` ] - Delogarithmise the responses for
% variables declared as `!variables:log`.
%
% * `'select='` [ cellstr | *`Inf`* ] - Run the shock response function for a
% selection of shocks only; `Inf` means all shocks are simulated.
%
% * `'size='` [ *'std'* | numeric ] - Size of the shocks that will be
% simulated; 'std' means that each shock will be set to its std dev
% currently assigned in the model object `m`.
%
% Description
% ============
%
% Example
% ========
%

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

opt = passvalopt('model.srf',varargin{:});

if ischar(opt.select)
    opt.select = regexp(opt.select,'\w+','match');
end

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

ne = sum(THIS.nametype == 3);
nalt = size(THIS.Assign,3);
elist = THIS.name(THIS.nametype == 3);

% Select shocks.
if isequal(opt.select,Inf)
    pos = 1 : ne;
else
    nsel = length(opt.select);
    pos = nan(1,nsel);
    for i = 1 : length(opt.select)
        x = find(strcmp(opt.select{i},elist));
        if length(x) == 1
            pos(i) = x;
        end
    end
    dochkshockselection();
end
SELECT = elist(pos);
nsel = length(SELECT);

% Set the size of the shocks.
if ischar(opt.size)
    shksize = THIS.stdcorr(1,pos,:);
else
    shksize = opt.size*ones(1,nsel,nalt);
end

func = @(T,R,K,Z,H,D,U,Omg,ialt,nper) ...
    timedom.srf(T,R(:,pos),[],Z,H(:,pos),[],U,[], ...
    nper,shksize(1,:,ialt));

[S,RANGE,SELECT] = myrf(THIS,TIME,func,SELECT,opt);

for i = 1 : length(SELECT)
    S.(SELECT{i}).data(1,i,:) = shksize(1,i,:);
    S.(SELECT{i}) = mytrim(S.(SELECT{i}));
end

% Nested functions.

%**************************************************************************
    function dochkshockselection()
        if any(isnan(pos))
            utils.error('model', ...
                'This is not a valid shock name: ''%s''.', ...
                opt.select{isnan(pos)});
        end
        nonun = strfun.nonunique(pos);
        if ~isempty(nonun)
            utils.error('model', ...
                'This shock name is requested more than once: ''%s''.', ...
                opt.select{nonun});
        end
    end
% dochkshockselection().

end