function this = exogenise(this,list,dates,flag)
% exogenise  Exogenise variables or re-exogenise shocks at the specified dates.
%
% Syntax
% =======
%
%     P = exogenise(M,LIST,DATES)
%     P = exogenise(M,DATES,LIST)
%     P = exogenise(M,LIST,DATES,FLAG)
%     P = exogenise(M,DATES,LIST,FLAG)
%
% Input arguments
% ================
%
% * `P` [ plan ] - Simulation plan.
%
% * `LIST` [ cellstr | char ] - List of variables that will be exogenised,
% or list of shocks that will be re-exogenised.
%
% * `DATES` [ numeric ] - Dates at which the variables will be exogenised.
%
% * `FLAG` [ 1 | 1i ] - Select the shock anticipation mode (when
% re-exogenising shocks); if not specified 1 is used.
%
% Output arguments
% =================
%
% * `P` [ plan ] - Simulation plan with new information on exogenised
% variables 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 exogenise an endogenous variable.
    index = strcmp(this.xlist,list{i});
    if any(index)
        this.xanchors(index,dates) = true;
    else
        % Try to re-exogenise a shock.
        index = strcmp(this.nlist,list{i});
        if any(index)
            if flag == 1
                this.nanchorsreal(index,dates) = false;
            else
                this.nanchorsimag(index,dates) = false;
            end
        else
            % Neither worked.
            valid(i) = false;
        end
    end
end

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

end