function d = array2db(X,range,name,logged,d)
% array2db  Convert numeric array to database.
%
% Syntax
% =======
%
%     d = array2db(X,range,name)
%
% Input arguments
% ================
%
% * `X` [ numeric ] - Numeric array with vectors of data in rows.
%
% * `range` [ numeric ] Date range corresponding to the columns of `X`.
%
% Output arguments
% =================
%
% * `d` [ struct ] - Output database.
%
% Description
% ============
%
% Example
% ========
% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if nargin < 4
  logged = false([1,size(X,1)]);
end

if nargin < 5
  d = struct();
end

if ~isnumeric(X) || ~isnumeric(range) ...
      || (~islogical(logged) && ~isstruct(logged)) || ~isstruct(d)
  error('Incorrect type of input argument(s).');
end

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

range = min(range) : max(range);
nx = size(X,1);
nalt = size(X,3);
nper = length(range);

template = tseries(range,zeros([nper,nalt]));
for i = 1 : nx
  Xi = permute(X(i,:,:),[2,3,1]);
  if (islogical(logged) && logged(i)) ...
        || (isstruct(logged) && logged.(name{i}))
    Xi = exp(Xi);
  end
  d.(name{i}) = replace(template,Xi);
end

end