function [x,newrange] = resize(x,range)
% resize  Clip tseries object down to specified date range.
%
% Syntax
% =======
%
%     x = resize(x,range)
%
% Input arguments
% ================
%
% * `x` [ tseries ] - Input tseries object whose date range will be clipped
% down.
%
% * `range` [ numeric ] - New date range to which the input tseries object
% will be clipped down.
%
% Output arguments
% =================
%
% * `x` [ tseries ] - Output tseries object with its date range clipped
% down to `range`.
%
% Description
% ============
%
% Example
% ========
%

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

% Parse input arguments.
P = inputParser();
P.addRequired('x',@(x) isa(x,'tseries'));
P.addRequired('range',@isnumeric);
P.parse(x,range);

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

if isempty(range) || isnan(x.start)
   newrange = [];
   x = empty(x);
   return
elseif all(isinf(range))
   newrange = x.start + (0 : size(x.data,1)-1);
   return
end

% Frequency of input tseries must be the same as frequency of new date
% range.
if ~all(freqcmp(range([1,end]),x.start))
   utils.error('tseries', ...
   ['Frequency of the tseries object and ', ...
   'the date frequency of the new range must be the same.']);
end

% Return immediately if start of new range is before start of input tseries
% and end of new range is after end of input tseries.
if round(range(1)) <= round(x.start) ...
      && round(range(end)) >= round(x.start + size(x.data,1) - 1)
   newrange = x.start + (0 : size(x.data,1)-1);
   return
end

if isinf(range(1))
   startdate = x.start;
else
   startdate = range(1);
end

if isinf(range(end))
   enddate = x.start + size(x.data,1) - 1;
else
   enddate = range(end);
end

newrange = startdate : enddate;
tmpsize = size(x.data);
nper = tmpsize(1);
index = round(newrange - x.start + 1);
deleteRows = index < 1 | index > nper;
newrange(deleteRows) = [];
index(deleteRows) = [];

if ~isempty(index)
   x.data = x.data(:,:);
   x.data = x.data(index,:);
   x.data = reshape(x.data,[length(index),tmpsize(2:end)]);
   x.start = newrange(1);
else
   x.data = zeros([0,tmpsize(2:end)]);
   x.start = NaN;
end

end
