function Y=mydetrend(X,T,DIM);
% MYDETREND Remove a linear trend from vector, matrix, or array
%
%   Y = mydetrend ( X, T, DIM )
%
%   Removes the best straight-line fit linear trend from
%   vector X and returns it in Y.
%
%   T is a vector of time: defaults to uniform time
%   spacing over first non-singleton dimension.
%
%   DIM is the dimension along which an array will be detrended:
%   default to first dimension that has same length as T.
%
%   The major difference with function DETREND is that it
%   can deal with nan's.

% D. Menemenlis (dimitri@pacific.jpl.nasa.gov), 15 mar 2000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% check input arguments
if nargin < 1
  error('missing arguments')
end
Xsize = size(X);                     % input array size
Xdim  = length(Xsize);               % input array dimension
if nargin < 2
  for i = 1:Xdim
    if Xsize(i) > 1
      DIM = i;
    end
  end
  T = 1:size(X,DIM);
end
nT = length(T);                      % number of timesteps
nX = prod(Xsize);                    % total number of points in X
if nT < 2
  error('wrong input arguments')
end
if nargin < 3
  for i = 1:Xdim
    if Xsize(i) == nT
      DIM = i;
    end
  end
end

% reshape input array into a matrix
X = shiftdim(X,DIM-1);
Wsize = size(X);                     % working array size
if length(Wsize) == 2 & Wsize(1) == 1
  Wsize = Wsize(2:-1:1);
end
X = reshape(X,Wsize(1),nX/Wsize(1));

% detrend column by column
for i=1:nX/Wsize(1)
  ix = find(~isnan(X(:,i)));
  if length(ix) > 1
    a = T (ix)';
    a = [a ones(size(a))];
    X(ix,i) = X(ix,i) - a * ( a \ X(ix,i) );
  end
end        

% reshape array to original dimension
X = reshape(X,Wsize);
Y = shiftdim(X,Xdim-DIM+1);
