function x = interp(x,range,varargin)
% interp  Interpolate missing observations.
%
% Syntax
% =======
%
%     x = interp(x,range,varargin)
%
% Input arguments
% ================
%
% * `x` [ tseries ] - Tseries object.
%
% * `range` [ tseries ] - Date range on which any missing, i.e. NaN,
% observations will be interpolated.
%
% Output arguments
% =================
%
% * `x` [ tseries ] - Tseries object with the missing observations
% interpolated.
%
% Options
% ========
%
% * `'method='` [ char | 'cubic' ] - Any valid method accepted by the
% built-in `interp1` function.
%
% Description
% ============
%
% Example
% ========
%

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

options = passvalopt('tseries.interp',varargin{:});

if nargin < 2
   range = Inf;
end

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

if any(isinf(range))
   range = get(x,'range');
elseif ~isempty(range)
   range = range(1) : range(end);
   x.data = rangedata(x,range);
   x.start = range(1);
else
   x = empty(x);
   return
end

data = x.data(:,:);
grid = dat2grid(range);
grid = grid - grid(1);
for i = 1 : size(data,2)
   index = ~isnan(data(:,i));
   if any(~index)
      data(~index,i) = interp1(...
         grid(index),data(index,i),grid(~index),options.method,'extrap');   
   end
end
x.data(:,:) = data;

end
