function [y, yd , ydd]  = polyval_Bonederiv(p, x, Th1,Th2, n)

% function [y, yd, ydd] = polyval_Bonederiv(p, x, Th, n)
%
% uses polyval to evaluate the derivative of the polynomial p and pNew at values of pixels of image 
% x that are between Th0 and Th1 and between Th1 and Th2. It creates the derivative bone segmentation function
%
% Written to be used with sir_bh_os.m
%
% Jeff Fessler, University of Michigan
% Monica Abella and Cristobal Martinez, Universidad Carlos III de Madrid

if nargin < 2
 error
end

if ~isvar('p') 
 error
end

if ~isvar('x')
 error
end

if ~isvar('Th1')
 Th1=0.3;
end


if ~isvar('Th2')
 Th2=0.98;
end

if ~isvar('n')
 n=0;
end

N=length(p);

if n==1
 pdot = [-(N-1:-1:1).*p(1:N-1), 0 0 ]; 
 pddot =[-(N:-1:0).*pdot, 0];
 x2=1./max(x, Th1);
else
 pdot = (N-1:-1:1).*p(1:N-1);
 pddot = (N-2:-1:1).*pdot(1:N-2);
 x2=x;
end

y = polyval(p,x2).*(x>Th1 & x<Th2);
 
yd = polyval(pdot,x2).*(x>Th1 & x<Th2);
     
ydd = polyval(pddot,x2).*(x>Th1 & x<Th2);
