function D = myhdata2tseries(THIS,H,RANGE,varargin)
% hdata2tseries  [Not a public function] Convert hdataobj data to a database with tseries.
%
% Backend IRIS function.
% No help provided.

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

isparams = ~any(strcmpi(varargin,'-noparams'));

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

maxlag = -min(imag(THIS.solutionid{2}));
xrange = RANGE(1)-maxlag : RANGE(end);
nxper = length(xrange);
template = tseries();

list = THIS.name(THIS.nametype <= 3);
nlist = length(list);
D = struct();
for i = 1 : nlist
    name = list{i};
    if ~isfield(H.data,name)
        continue
    end
    comment = THIS.namelabel{i};
    s1 = size(H.data.(name),1);
    s2 = size(H.data.(name),2);
    s3 = size(H.data.(name),3);
    s4 = size(H.data.(name),4);
    if s1 ~= nxper
        utils.error('hdataobj','Internal IRIS error.');
    end
    if THIS.log(i)
        H.data.(name) = exp(H.data.(name));
    end
    D.(name) = template;
    D.(name).start = xrange(1);
    D.(name).data = H.data.(name);
    H.data.(name) = [];
    D.(name).Comment = cell(1,s2,s3,s4);
    D.(name).Comment(:) = {comment};
    D.(name).UserData = [];
    D.(name) = mytrim(D.(name));
end

if isparams
    for i = find(THIS.nametype == 4)
        name = THIS.name{i};
        D.(name) = permute(THIS.Assign(1,i,:),[1,3,2]);
    end
end

end