function Rf = refine2(g1,K,Rf)
% Rf = refine2(m,n,a,b,Rf);
% refine local minima and maxima using Newton's
% method for the functions fir_fer.m and fir_rfer.m.
% Author: Ivan W. Selesnick, Rice University

w = Rf(:);
g1 = g1(:);
M = length(g1)-1;
m = 0:M;

for k = 1:4

   G1_0 =  cos(w*m) * g1;
   G1_1 = -sin(w*m) * (m'.*g1);
   G1_2 = -cos(w*m) * (m'.*m'.*g1);
   
   G2_0 = (1-cos(w)).^K;
   G2_1 = K*(1-cos(w)).^(K-1).*sin(w);
   G2_2 = K*(1-cos(w)).^(K-1).*cos(w) + K*(K-1)*(1-cos(w)).^(K-2).*sin(w).*sin(w);

   H_1 = -G1_0.*G2_1 - G1_1.*G2_0;
   H_2 = -G1_0.*G2_2 - 2*G1_1.*G2_1 - G1_2.*G2_0;

   w = w - H_1./H_2;
end
Rf(:) = w;

