function detrend(ts,type,varargin) 
%DETREND  Detrend time series data
%
%   DETREND(TS,TYPE,VARARGIN) removes a linear trend from data in a time 
%   series object, usually for FFT processing. TYPE is a string, either 
%   'constant' or 'linear', which describes the detrending method.
%
%   DETREND also removes all NaNs from the data.
%
%   See also TSDATA.TIMESERIES/TIMESERIES

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

%% Optional 3rd argument limits detending to the specifed columns

s = size(ts.Data);

%% Detrends time series data
if (length(s)>2 && ts.DataInfo.GridFirst) || ...
        (s(2)>1 && ~ts.DataInfo.GridFirst) || length(s)>3
    error('timeseries:idealfilter:noarray',...
        'idealfilter cannot be applied to >2 dimensional time series data')
end

%% Get column indices
if nargin>=3 && isnumeric(varargin{1})
    colind = varargin{1};
else
    if ts.DataInfo.GridFirst
        colind = 1:s(end);
    else
        colind = 1:s(1);
    end
end

%% Detrend the ordinate data
if ts.DataInfo.GridFirst
    data = ts.Data(:,colind);
    for col=1:length(colind)
        nanvals = isnan(data(:,col));
        % If there are than two non-nan samples - do nothing
        if sum(~nanvals)>2
            data(~nanvals,col) = detrend(data(~nanvals,col),type);
        end
    end   
    ts.Data(:,colind) = data;
else
    data = ts.Data(colind,1,:);
    for col=1:length(colind)
        nanvals = isnan(squeeze(data(col,1,:))); 
        % If there are than two non-nan samples - do nothing
        if sum(~nanvals)>2
            data(col,1,~nanvals) = ...
                reshape(detrend(squeeze(data(col,1,~nanvals))',type)',...
                [1 1 sum(~nanvals)]);
        end
    end
    ts.Data(colind,1,:) = data;
end
