function fprime=fnder(f,dorder)
% FNDER	Differentiate a spline or pp.
 
%        fprime=fnder(f[,dorder])
%
%  returns the (representation of the) dorder-th derivative of the function 
%  contained in  f  (and in the same form). dorder=1  is the default.

% C. de Boor / latest change: Feb.25, 1989
% Copyright (c) 1990-92 by Carl de Boor and The MathWorks, Inc.

if (nargin<2), dorder=1;end

if (f(1)==10), % the function is in pp-representation:
   [breaks,coefs,l,k,d]=ppbrk(f);
   if (k<=dorder)
      fprime=ppmak([breaks(1) breaks(l+1)],zeros(d,1));
   else
      knew=k-dorder;
      for j=k-1:-1:knew;
         coefs=coefs.*(ones(d*l,1)*[j:-1:j-k+1]);
      end
      fprime=ppmak(breaks,coefs(:,1:knew),d);
   end
elseif (f(1)==11), % the function is in B-repr.; omit trivial B-spline terms.
   [t,a,n,k,d]=spbrk(f);
   if(k<=dorder);
      fprime=spmak(t,zeros(d,n),d);
   else
      knew=k-dorder;
      for j=k-1:-1:knew;
         tt=t(j+1+[0:n])-t(1:n+1);z=find(tt>0);nn=length(z);
         (diff([zeros(1,d);a';zeros(1,d)]))';
         a=ans(:,z)./(ones(d,1)*(tt(z)/j));
         t=[t(z) t(n+2:n+j+1)];n=nn;
      end
      fprime=spmak(t,a);
   end
else,  % unknown representation
   error('unknown function type encountered')
end
