function [y,range] = rangedata(x,range)
% rangedata  Retrieve tseries data from a continuous range.
%
% Syntax
% =======
%
%     [y,range] = rangedata(x,range)
%     [y,range] = rangedata(x,[startdate,enddate])
%
% Input arguments
% ================
%
% * `x` [ tseries ] - Tseries object.
%
% * `range` [ numeric ] - A continuous date range; data from range(1) to
% range(end) will be returned.
%
% * `startdate` [ numeric ] - Start date of the range.
%
% * `enddate` [ numeric ] - End date of the range.
%
% Output arguments
% =================
%
% * `y` [ numeric ] - Output data.
%
% * `range` [ numeric ] - The actual entire date range from which the data
% come.
%
% Description
% ============
%
% The `rangedata` function is equivalent to calling
%
%     y = x(range(1):range(end));
%
% but it designed to be more efficient for the special case of contiunous
% date ranges.
%}

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

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

if nargin == 1
   y = x.data;
   range = [x.start,x.start+size(x.data,1)-1];
   return
end

tmpsize = size(x.data);
if isempty(range) || isequalwithequalnans(range,NaN)
   y = zeros([0,tmpsize(2:end)]);
   return
end

if isnan(x.start) || isempty(x.data)
   y = nan([round(range(end)-range(1)+1),tmpsize(2:end)]);
   return
end

ncol = prod(tmpsize(2:end));

if isinf(range(1))
   % Range is Inf or [-Inf,...].
   startindex = 1;
else
   startindex = round(range(1) - x.start + 1);
end

if isinf(range(end))
   % Range is Inf or [...,Inf].
   endindex = tmpsize(1);
else
   endindex = round(range(end) - x.start + 1);
end

if startindex > endindex
   y = nan([0,ncol]);
elseif startindex >= 1 && endindex <= tmpsize(1)
   y = x.data(startindex:endindex,:);
elseif (startindex < 1 && endindex < 1) || (startindex > tmpsize(1) && endindex > tmpsize(1))
   y = nan([endindex-startindex+1,ncol]);
elseif startindex >= 1
   y = [x.data(startindex:end,:);nan([endindex-tmpsize(1),ncol])];
elseif endindex <= tmpsize(1)
   y = [nan([1-startindex,ncol]);x.data(1:endindex,:)];
else
   y = [nan([1-startindex,ncol]);x.data(:,:);nan([endindex-tmpsize(1),ncol])];
end

if length(tmpsize) > 2
   y = reshape(y,[size(y,1),tmpsize(2:end)]);
end

% Return actual range if requested.
if nargout > 1
   range = x.start + (startindex : endindex) - 1;
end

end
