clc; clear all; close all;

% Please modify testfile.
A =load('PNdata_two_5MHz_OCXO__170dBC.csv');

% 2 same samples, OFF3 = 3, else OFF3 = 0.
OFF3 = 3; 

ss ='PN2060A 5M OCXO 500-01281C, Spur removel';

size(A)

freq = A(:,1);

PN_Re = A(:,2);
PN_Im = A(:,3);

Per_IM = 30;
avg = ones(1, Per_IM)/Per_IM;

avgIm = filter(avg, 1, PN_Im);


PN_Re_noSpur = medfilt1(PN_Re,10);

Per = 3;
avg = ones(1, Per)/Per;
avgRe = filter(avg, 1, PN_Re_noSpur);


figure(2);
semilogx(freq(Per_IM:end), avgIm(Per_IM:end),'-b');
hold on;
semilogx(freq, PN_Re-OFF3,'-.c');
grid on;
hold on;
semilogx(freq, avgRe-OFF3,'-k');

title(ss);

xlim([10^-1 10^6]);
ylim([-190 -10]);
yticks([-190:10:-10]);

t=0;
f1 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>1
       f1 = i;
       break;
   end
end
f2 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>10
       f2 = i;
       break;
   end
end
f3 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>100
       f3 = i;
       break;
   end
end
f4 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>1000
       f4 = i;
       break;
   end
end
f5 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>10000
       f5 = i;
       break;
   end
end
f6 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>100000
       f6 = i;
       break;
   end
end

f7 = 0;
for i = 1:length(freq)
    t = freq(i);
   if t>800000
       f7 = i;
       break;
   end
end

plot(freq(f1), avgRe(f1)-OFF3, 'r+');    % 标记点
plot(freq(f2), avgRe(f2)-OFF3, 'r+');    % 标记点
plot(freq(f3), avgRe(f3)-OFF3, 'r+');    % 标记点
plot(freq(f4), avgRe(f4)-OFF3, 'r+');    % 标记点
plot(freq(f5), avgRe(f5)-OFF3, 'r+');    % 标记点
plot(freq(f6), avgRe(f6)-OFF3, 'r+');    % 标记点
plot(freq(f7), avgRe(f7)-OFF3, 'r+');    % 标记点

ch = sprintf("%3.1f dBC/Hz",avgRe(f1)-OFF3);
text(freq(f1),avgRe(f1)-3+5,ch);

ch = sprintf("%3.1f dBC/Hz",avgRe(f2)-OFF3);
text(freq(f2),avgRe(f2)-3+5,ch);

ch = sprintf("%3.1f dBC/Hz",avgRe(f3)-OFF3);
text(freq(f3),avgRe(f3)-3+5,ch);

ch = sprintf("%3.1f dBC/Hz",avgRe(f4)-OFF3);
text(freq(f4),avgRe(f4)-3+10,ch);

ch = sprintf("%3.1f dBC/Hz",avgRe(f5)-OFF3);
text(freq(f5),avgRe(f5)-3+10,ch);

ch = sprintf("%3.1f dBC/Hz",avgRe(f6)-OFF3);
text(freq(f6),avgRe(f6)-3+10,ch);

ch = sprintf("%3.1f dBC/Hz @%0.0fHz",avgRe(f1)-OFF3, freq(f1));
text(freq(f5),-60,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fHz",avgRe(f2)-OFF3, freq(f2));
text(freq(f5),-65,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fHz",avgRe(f3)-OFF3, freq(f3));
text(freq(f5),-70,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fKHz",avgRe(f4)-OFF3, freq(f4)/1000);
text(freq(f5),-75,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fKHz",avgRe(f5)-OFF3, freq(f5)/1000);
text(freq(f5),-80,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fKHz",avgRe(f6)-OFF3, freq(f6)/1000);
text(freq(f5),-85,ch);
ch = sprintf("%3.1f dBC/Hz @%0.0fKHz",avgRe(f7)-OFF3, freq(f7)/1000);
text(freq(f5),-90,ch);

hold off;
