function [D,X] = mydtrends(THIS,TTREND,PINDEX,IALT)
% XXDTRENDS  [Not a public function] Return dtrends coefficient matrices.
%
% Backed IRIS function.
% No help provided.

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

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

isx = nargout > 1;
npout = numel(PINDEX);
nper = numel(TTREND);
nname = length(THIS.name);
ny = sum(THIS.nametype == 1);

% Return the matrix of deterministic regressors, `D`, and impact
% matrix for out-of-likelihood parameters, `X`.
D = zeros(ny,nper);
X = zeros(ny,npout,nper);

% Get the requested parameterisation.
x0 = THIS.Assign(1,:,IALT);

% Reset out-of-likelihood parameters to zero.
if npout > 0
    x0(1,PINDEX) = 0;
end

occur = THIS.occur(THIS.eqtntype == 3,(THIS.tzero-1)*nname+(1:nname));
eqtn = THIS.eqtnF(THIS.eqtntype == 3);
deqtn = THIS.deqtnF(THIS.eqtntype == 3);

for i = 1 : ny
    D(i,:) = eqtn{i}(x0,1,TTREND);
    if isx && ~isempty(PINDEX)
        parametersinthisdtrend = find(occur(i,:));
        for j = 1 : npout
            index = parametersinthisdtrend == PINDEX(j);
            if any(index)
                % Evaluate derivatives of dtrends equation w.r.t.
                % out-of-likelihood parameters. size of d is nocc-by-nper.
                if isempty(deqtn{i}) || isempty(deqtn{i}{index})  ...
                        || ~isa(deqtn{i}{index},'function_handle')
                    utils.error('model', ....
                        ['This model object has been loaded from a disk file ', ...
                        'created in an older version of IRIS, and is not ', ...
                        'compatible. You must re-create the model object from ', ...
                        'from the original model file.']);
                end
                X(i,j,:) = deqtn{i}{index}(x0,1,TTREND);
            end
        end
    end
end

end
% xxdtrends().