%reg_exampleP_opt
%cc
%example of restoration of a signal from blurred noised input by
%parameterized spline with optimal parameter
load NL
%rho=.01
ToX=.000001;
range_rho1=1000;%input('range_rho1; 111-former; ?')
if range_rho1~=111
    range_rho=[0 range_rho1];
end
r=2;
Par=2*r;
q=2;
S=4;
lx=256;
n=0:lx-1;
   si=sin(pi*n/lx);
   W=(2*si).^(2*r);
  [ur,~]=juviP(2*r,lx); 
   [uq,~]=juviP(q,lx); 
  [urq,~]=juviP((2*r+q),lx);  
h = fspecial('gaussian',[1, lx],S);
h=double(h);
figure;subplot(3,2,1)
plot(h,'k','LineWidth',2);
title(['\fontsize{16}Kernel: STD='  num2str(S,2) ])
h=lshuk((lx/2-1),h,1);

fh=(fft(h));
subplot(3,2,2);plot(abs(fh(1:lx/2)),'k','LineWidth',2);
title(['\fontsize{16}DFT of kernel: STD='  num2str(S,2) ])

F=nloch;

fF=fft(F);
nois=.02*randn(1,lx);
fnois=fft(nois);
ee=sum(nois(:).^2);

fG=(fF.*fh);
G=real(ifft(fG));
subplot(3,2,3)
plot(F,'k','LineWidth',1);
hold on
plot(G,'b','LineWidth',2);
title(['\fontsize{16}Original vs. blurred' ])
subplot(3,2,4)
plot(abs(fF(4:lx/4)),'k','LineWidth',1);
hold on
plot(abs(fG(4:lx/4)),'b','LineWidth',2);
title(['\fontsize{16}DFT Original vs. blurred (fragment)' ])
nG=G+nois;
nfG=fG+fnois;
subplot(3,2,5)
plot(F,'k','LineWidth',1);
hold on
plot(nG,'b','LineWidth',2);
title(['\fontsize{16}Original vs. noised blurred' ])
subplot(3,2,6)
plot(abs(fF(4:lx/4)),'k','LineWidth',1);
hold on
plot(abs(nfG(4:lx/4)),'b','LineWidth',2);
title(['\fontsize{16}DFT Original vs.  noised  blurred (fragment)' ])

rho=defroP_conv(Par,q,nG,fh./uq,ee,range_rho,ToX)% derivation of the optimal parameter

H=conj(fh).*urq./uq;

d=H.*ur./(rho*W.*ur+abs(H.^2));
fSG=d.*nfG;
nF=real(ifft(fSG));
figure;
subplot(2,2,1)
plot(abs(d(1:lx/2)),'b','LineWidth',2);
title(['\fontsize{16}DFT of d_{\rho}, \rho=' num2str(rho,3) ])

subplot(2,2,2)
plot(F,'k','LineWidth',1);
title(['\fontsize{16}Restored vs. original ' ])
hold on
plot(nF,'b','LineWidth',2);
hold on
plot(nG,'b--','LineWidth',1);
subplot(2,2,3)
plot(abs(fF(1:lx/2)),'k','LineWidth',1);
title(['\fontsize{16}DFT of restored vs. original ' ])
hold on

plot(abs(fSG(1:lx/2)),'b','LineWidth',2);
hold on

plot(abs(nfG(1:lx/2)),'b--','LineWidth',1);

subplot(2,2,4)
plot(abs(fF(4:lx/4)),'k','LineWidth',1);
title(['\fontsize{16}DFT of restored vs. original (fragment) ' ])
hold on

plot(abs(fSG(4:lx/4)),'b','LineWidth',2);
hold on

plot(abs(nfG(4:lx/4)),'b--','LineWidth',1);
