% auxiliary routine for gcvdemo
% finds the optimal threshold

figure(1)
sigvar = var(nonoise,1);

thmax = max(abs(waveletcoef((2^(L)+1):n)));
m = 50;
eind = thmax/8;

disp('Compute and estimate the error of the result');
disp('...in practice we can not compute the error of the result exactly');
disp('   because we do not know the exact signal...');

for i = 1:m
  th(i) = i * eind / m;
  wna = waveletcoef;
  coefnonoise = FWT_BIO(nonoise,L,ht,gt,sht,sgt);
  gcv(i) = GCV(waveletcoef((2^(L)+1):n),th(i));
  mse(i) = MSE(coefnonoise,waveletcoef,th(i));
end

figure(3), subplot(1,1,1), plot(th,gcv,'r')
hold on, plot(th,mse), hold off
pause(-1)
title('looking for the best threshold')
text(th(fix(m*0.75)), gcv(fix(m*0.75))*1.1,'estimated error (GCV)')
text(th(fix(m*0.75)), mse(fix(m*0.75))*1.1,'real error')

%initialisation Fibonacci - numbers

F0 = 1;
F1 = 1;
F2 = 2;
numbr = 1;

disp('Looking for optimal threshold...')

% compute the number of steps needed

m = 50;
b = eind; 
a =  b / m; %(in 0 we can not compute GCV)
eps = 0.0001;
while (b - a) / F2 > eps
  F0 = F1;
  F1 = F2;
  F2 = F0 + F1;
  numbr = numbr + 1;
end
v = a + (F1/F2) * (b - a);
fv = GCV(waveletcoef((2^(L)+1):n),v); 
u = a + (F0/F2) * (b - a);
fu = GCV(waveletcoef((2^(L)+1):n),u);

for k = 1:numbr - 1
 if (fu > fv)
    a = u;
    u = v;
    fu = fv;
    v = b-u+a;
    fv = GCV(waveletcoef((2^(L)+1):n),v);
 else
    b = v;
    v = u;
    fv = fu;
    u = a+b-v;
    fu = GCV(waveletcoef((2^(L)+1):n),u);
 end
end

bestthreshold = (a+b)/2
thrshld = bestthreshold;
