function d = dbclip(d,range)
% dbclip  Clip all database tseries objects down to specified date range.
%
% Syntax
% =======
%
%     d = dbclip(d,range)
%
% Input arguments
% ================
%
% * `d` [ struct ] - Database or nested databases with tseries objects.
%
% * `range` [ numeric ] - Range to which all tseries objects will be
% clipped.
%
% Output arguments
% =================
%
% * `d` [ struct ] - Database with tseries objects cut down to `range`.
%
% Description
% ============
%
% This functions looks up all tseries objects within the database `d`,
% including tseries objects nested in sub-databases, and cuts off any
% values preceding the start date of `range` or following the end date of
% `range`. The tseries object comments, if any, are preserved in the new
% database.
%
% Example
% ========
%
%     d = struct();
%     d.x = tseries(qq(2005,1):qq(2010,4),@rand);
%     d.y = tseries(qq(2005,1):qq(2010,4),@rand)
%
%     d =
%        x: [24x1 tseries]
%        y: [24x1 tseries]
%
%     dbclip(d,qq(2007,1):qq(2007,4))
%
%     ans =
%         x: [4x1 tseries]
%         y: [4x1 tseries]

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

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

list = fieldnames(d);
tseriesIndex = structfun(@istseries,d);
structIndex = structfun(@isstruct,d);

% Cycle over all tseries objects.
for i = find(tseriesIndex.')
    [data,tempRange] = rangedata(d.(list{i}),range);
    if isempty(data)
        tempRange = NaN;
    end
    d.(list{i}).data = data;
    d.(list{i}).start = tempRange(1);
end

% Call recusively `dbclip` on sub-databases.
for i = find(structIndex.')
    d.(list{i}) = dbclip(d.(list{i}),range);
end

end
