clear all;
close all;

samples=load("maser_equal_file.txt");

n_samples=length(samples)
n_center=floor(n_samples/2)
corr_start_n=376; %680;
corr_end_n=428; %688;

%samples=median(samples,10);
samples(510)=samples(509);
samples(511)=samples(509);
samples(512)=samples(509);
samples(513)=samples(515);
samples(514)=samples(515);



y1=samples(corr_start_n);
y2=samples(corr_end_n);
dx=(y2-y1)/(corr_end_n-corr_start_n);
y_tmp=[y1:dx:y2];
samples=[samples(1:corr_start_n-1);y_tmp';samples(corr_end_n:end-1)];


%samples_a=samples(150:n_center);
%samples_b=samples(n_center+1:1024-150);
%xtmp1=[150:n_center]';
%mod1=polyfit(xtmp1,samples_a,2);
%xtmp2=[1:n_center-150]';
%mod2=polyfit(xtmp2,samples_b,2);
%xtmp1b=[1:512];
%ytmp1b=polyval(mod1,xtmp1b);
%xtmp2b=[1:512];
%ytmp2b=polyval(mod2,xtmp2b);
%ytmp_filt=[ytmp1b ytmp2b];

%xtmp=[1:n_samples];
%mod=polyfit(xtmp(100:n_samples-100),samples(100:n_samples-100),4);
%ytmp_filt=polyval(mod,xtmp);

xtmp=[1:n_samples];
%test_zoom=samples(100:n_samples-100);
%test_freq=xtmp(100:n_samples-100);
test_zoom=samples(50:n_samples-50);
test_freq=xtmp(50:n_samples-50);

%mod1=splinefit(test_freq,test_zoom, 7, "robust", 0.7);
%mod1=splinefit(test_freq,test_zoom, 11, "robust", 0.7);
mod1=splinefit(test_freq,test_zoom, 15, "robust", 0.2);
samples2=ppval(mod1,xtmp);
test=length(samples2)

samples_dB=10*log10(samples);
samples2_dB=10*log10(samples2);

samples_error_dB=samples_dB'-samples2_dB;


figure(1)
hold on;
plot(samples_dB,'r');
plot(samples2_dB,'b');
grid on;
ylim([30 50]);
hold off;

figure(2)
hold on;
plot(samples_error_dB,'r');
grid on;
ylim([-0.5 0.5]);
hold off;

%save -ascii "maser_equal_file.txt" samples3
