function DATA = outputdata(THIS,FORMAT,RANGE,X,P,NAMES) %#ok<INUSL>
% outputdata  [Not a public function] VAR output data.
%
% Backend IRIS function.
% No help provided.

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

if ~exist('P','var')
    P = [];
end

if ~exist('NAMES','var')
    NAMES = {};
end

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

nx = size(X,1);
RANGE = RANGE(1) : RANGE(end);
nper = numel(RANGE);
ndata3 = size(X,3);
ndata4 = size(X,4);

% Prepare array of std devs if cov matrix is supplied.
if numel(P) == 1 && isnan(P)
    nstd = size(X,1);
    std = nan(nstd,nper,ndata3,ndata4);
elseif ~isempty(P)
    P = timedom.fixcov(P);
    nstd = min([size(X,1),size(P,1)]);
    std = zeros(nstd,nper,ndata3,ndata4);
    for i = 1 : ndata3
        for j = 1 : ndata4
            for k = 1 : nstd
                std(k,:,i,j) = permute(sqrt(P(k,k,:,i,j)),[1,3,2,4,5]);
            end
        end
    end
end

if strcmpi(FORMAT,'auto')
    if isempty(NAMES)
        FORMAT = 'tseries';
    else
        FORMAT = 'dbase';
    end
end

switch FORMAT
    case 'tseries'
        template = tseries();
        dotseries();
    case 'dbase'
        template = tseries();
        dostruct();
    case 'array'
        doarray();
end

% Nested functions.

%**************************************************************************
    function dotseries()
        if isempty(P)
            DATA = replace(template,permute(X,[2,1,3,4]),RANGE(1));
        else
            DATA = struct();
            DATA.mean = replace(template,permute(X,[2,1,3,4]),RANGE(1));
            DATA.std = replace(template,permute(std,[2,1,3,4]),RANGE(1));
        end
    end
% dotseries().

%**************************************************************************
    function dostruct()
        DATA = struct();
        for ii = 1 : nx
            DATA.(NAMES{ii}) = ...
                replace(template,permute(X(ii,:,:,:),[2,3,4,1]),RANGE(1));
        end
        if ~isempty(P)
            DATA = struct('mean',DATA,'std',struct());
            for ii = 1 : nstd
                DATA.std.(NAMES{ii}) = ...
                    replace(template,permute(std(ii,:,:,:),[2,3,4,1]),RANGE(1));
                DATA.std.(NAMES{ii}) = mytrim(DATA.std.(NAMES{ii}));
            end
        end
    end
% dostruct().

%**************************************************************************
    function doarray()
        if isempty(P)
            DATA = permute(X,[2,1,3,4]);
        else
            DATA = struct();
            DATA.mean = permute(X,[2,1,3,4]);
            DATA.std = permute(std,[2,1,3,4]);
        end
    end
% doarray().

end
