function zd=dtrend(z,o,brp)
%DTREND removes trends from data sets
%
%	ZD = dtrend(Z)    or   ZD = dtrend(Z,O,BREAKPOINTS)
%
%	Z is the data set to be detrended, organized with the data records as
%	column vectors. ZD is returned as the detrended data.
%	
%	If O = 0 (the default case) the sample means are removed from each of
%	the columns.
%
%	If O = 1, linear trends are removed. A continuous, piecewise linear
%	trend is adjusted to each of the data records, and then removed. The
%	interior breakpoints for the linear trend segments are contained in
%	the row vector BREAKPOINTS. The default value is that there are no
%	interior breakpoints, so that one single straight line is removed from
%	each of the data records.

%	L. Ljung 7-8-87
%	Copyright (c), 1987-90 The MathWorks, Inc.
%	All Rights Reserved

[N,nz]=size(z);
if nargin<3,brp=[];end
if nargin<2,o=0;end
if o==1
   lb=length(brp);if lb==0,brp=1;lb=1;else
   if length(find(brp==1))==0,
   brp(2:lb+1)=brp;brp(1)=1;end,end
   lb=length(brp);if brp(lb)>=N,lb=lb-1;end
   for k=1:nz
    phi=zeros(lb+1,N);
    phi(1,:)=ones(1,N);
    for kb=1:lb
    int=[brp(kb):N];
    phi(kb+1,int)=10*(int-int(1))/N;
    end
    zd(:,k)=z(:,k)-phi'*(phi'\z(:,k));
    end
end
if o==0
	for k=1:nz
	zd(:,k)=z(:,k)-mean(z(:,k));
	end
end
