function idealfilter(ts,intervals,type,varargin) 
%IDEALFILTER  Apply an ideal (non-causal) filter to a time series object.
%
%   TS2=IDEALFILTER(TS1,INTERVALS,TYPE,VARARGIN) applies an ideal filter of
%   TYPE "pass" or "notch" to the specified frequency intervals, INTERVALS. 
%   When nesessary the time series is resampled to be uniform and NaNs are
%   interpolated. Optional 4th argument limits the filtering to specified 
%   columns.
%
%   INTERVALS are an nx2 array of frequencies where n = number of
%   intervals.
%
%   See also TSDATA.TIMESERIES/TIMESERIES, TSDATA.TIMESERIES/FILTER

%   Author(s): James G. Owen
%   Copyright 1986-2004 The MathWorks, Inc.
%   $Revision: 1.1.6.1 $  $Date: 2004/12/26 21:35:06 $

%% Intervals are an nx2 array of frequencies where n = number of intervals
s = size(ts.Data);
if length(s)>2
    error('timeseries:idealfilter:noarray',...
        'idealfilter cannot be applied to >2 dimensional time series data')
end
if nargin<=3
    colind = 1:s(2);
else
    colind = varargin{1};
end

%% N0-op for scalars
if ts.TimeInfo.Length<=1
    return
end

%% If the time series is non-uniformply sampled or has NaN values
%% then resample
nandata = isnan(ts.Data(:,colind));
if isnan(ts.TimeInfo.Increment) || any(nandata(:))
    time = ts.Time;    
    tuniform = time(1):min(diff(time)): time(end);
    ts.resample(tuniform);
    s = size(ts.Data);
end

%% Detrend the ordinate data
ts.detrend('constant',colind);

%% Find the fft
Ts = ts.timeInfo.Increment;
idata = fft(ts.Data(:,colind));
fdata = (0:(s(1)-1))/(s(1)*Ts);
fdata(fdata>1/(2*Ts)) = 1/Ts - fdata(fdata>1/(2*Ts));

%% Null out excluded frequencies
if strcmpi(type,'pass')
   I = true(size(fdata));
else
   I = false(size(fdata));
end
for ct=1:size(intervals,1)
   if strcmpi(type,'pass')
       I = I & (fdata<=min(intervals(ct,:)) | fdata>max(intervals(ct,:)));   
   else
       I = I | (fdata>min(intervals(ct,:)) & fdata<=max(intervals(ct,:)));
   end
end
idata(I,:) = 0;

%% Reset the time series data
ts.Data(:,colind) = ifft(idata);
