function OPT = mypreoutput(THIS,XRANGE,NDATA,OPT)
% MYPREOUTPUT  [Not a public function] Prepare memory-intensitve output data.
%
% Backend IRIS function.
% No help provided.

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

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

nalt = size(THIS.Assign,3);
OPT.nloop = max(NDATA,nalt);
nloop = OPT.nloop;
try
    prec = OPT.precision;
catch %#ok<CTCH>
    prec = 'double';
end


H = struct();

dopopulateret();

% Kalman filter smoother data and simulate/forecast output.
if OPT.retsmooth
    H.smoothmean = hdataobj(THIS,'mean',XRANGE,prec,nloop);
    if OPT.returnstd && ~OPT.meanonly
        H.smoothstd = hdataobj(THIS,'std',XRANGE,prec,nloop);
    end
    if OPT.returnmse && ~OPT.meanonly
        H.smoothmse = hdataobj(THIS,'mse',XRANGE,prec,nloop);
    end
end

% Kalman filter prediction data.
if OPT.retpred
    n = max(nloop,OPT.ahead);
    H.predmean = hdataobj(THIS,'mean',XRANGE,prec,n);
    H.predmean.opt.lags = false;
    if OPT.returnstd && ~OPT.meanonly
        H.predstd = hdataobj(THIS,'std',XRANGE,prec,nloop);
        H.predstd.opt.lags = false;
    end
    if OPT.returnmse && ~OPT.meanonly
        H.predmse = hdataobj(THIS,'mse',XRANGE,prec,nloop);
        H.predmse.opt.lags = false;
    end
end

if OPT.retf
    H.f = hdataobj(THIS,'f',XRANGE,prec,nloop);
end

if OPT.retpe
    n = max(nloop,OPT.ahead);
    H.pe = hdataobj(THIS,'pe',XRANGE,prec,n);
end

if OPT.retpevec
    n = max(nloop,OPT.ahead);
    H.pevec = hdataobj(THIS,'pevec',XRANGE,prec,n);
end

if isempty(fieldnames(H))
    H = [];
end

OPT.outputdata = H;

% Nested functions.

%**************************************************************************
    function dopopulateret()
        % Populate all possible ret fields with default values in the option
        % struct.
        x = struct();
        x.meanonly = true;
        x.returnmse = false;
        x.returnstd = false;
        x.retsmooth = false;
        x.retpred = false;
        x.retf = false;
        x.retpe = false;
        x.retpevec = false;
        list = fieldnames(x);
        nlist = length(list);
        for i = 1 : nlist
            if ~isfield(OPT,list{i})
                OPT.(list{i}) = x.(list{i});
            end
        end
    end
% dopopulateret().

end