function this = endogenise(this,list,dates,flag)
% endogenise  Endogenise shocks or re-endogenise variables at the specified dates.
%
% Syntax
% =======
%
%     P = endogenise(P,LIST,DATES)
%     P = endogenise(P,DATES,LIST)
%     P = endogenise(P,LIST,DATES,FLAG)
%     P = endogenise(P,DATES,LIST,FLAG)
%
% Input arguments
% ================
%
% * `P` [ plan ] - Simulation plan.
%
% * `LIST` [ cellstr | char ] - List of shocks that will be endogenised, or
% list of variables that will be re-endogenise.
%
% * `DATES` [ numeric ] - Dates at which the shocks or variables will be
% endogenised.
%
% * `FLAG` [ 1 | 1i ] - Select the shock anticipation mode; if not
% specified 1 is used.
%
% Output arguments
% =================
%
% * `P` [ plan ] - Simulation plan with new information on endogenised
% shocks included.
%
% Description
% ============
%
% Example
% ========
%

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

if nargin < 4
    flag = 1;
end

if isnumeric(list) && (ischar(dates) || iscellstr(dates))
    [list,dates] = deal(dates,list);
end

% Parse required input arguments.
P = inputParser();
P.addRequired('p',@isplan);
P.addRequired('list',@(x) ischar(x) || iscellstr(x));
P.addRequired('dates',@isnumeric);
P.addRequired('flag',@(x) isnumericscalar(x) && (x == 1 || x == 1i));
P.parse(this,list,dates,flag);

% Convert char list to cell of str.
if ischar(list)
    list = regexp(list,'[A-Za-z]\w*','match');
end

if isempty(list)
    return
end

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

[dates,outofrange] = mydateindex(this,dates);

if ~isempty(outofrange)
    % Report invalid dates.
    utils.error('plan', ...
        'Dates out of simulation plan range: %s.', ...
        dat2charlist(outofrange));
end

nlist = numel(list);
valid = true([1,nlist]);

for i = 1 : nlist
    % Try to endogenise a shock.
    index = strcmp(this.nlist,list{i});
    if any(index)
        if flag == 1
            this.nanchorsreal(index,dates) = true;
        else
            this.nanchorsimag(index,dates) = true;
        end
    else
        % Try to re-endogenise an endogenous variable.
        index = strcmp(this.xlist,list{i});
        if any(index)
            this.xanchors(index,dates) = false;
        else
            % Neither worked.
            valid(i) = false;
        end
    end
end

% Report invalid names.
if any(~valid)
    utils.error('plan', ...
        'Cannot endogenise this name: ''%s''.', ...
        list{~valid});
end

end