
segs{1} = 'seg20';
segs{2} = 'seg21';
segs{3} = 'seg22';
segs{4} = 'seg23';
segs{5} = 'seg24';
segs{6} = 'seg20';
segs{7} = 'seg22';
segs{8} = 'seg24';

basepath = 'D:\data\'; %chan2\seg21\mcords.rec002.r1-2.20111010015404.0000.dat';

for adc = 2
  fn = get_filename(fullfile(basepath,sprintf('chan%d',adc),segs{adc}),'mcords','','.0000.dat')
  [hdr,data] = basic_load_mcords(fn,struct('clk',1e9/9,'first_byte',2^26));
  
  for wf = 1:2
    
    mean_data = double(mean(data{wf}(1:end-1,:),2));
    
    fs = 1e9/9;
    dt = 1/fs;
    Nt = length(mean_data);
    time = hdr.wfs(wf).t0 - 11e-6 + dt*(0:Nt-1).';
    
    td_delay_line = 21.44e-6;
    f0 = 189.15e6;
    f1 = 198.65e6;
    fc = (f0+f1)/2;
    BW = f1 - f0;
    Tpd(1) = 1e-6;
    Tpd(2) = 10e-6;
    alpha = BW/Tpd(wf);
    
    hdr.wfs(wf).num_sam
    good_rbins = find(time >= td_delay_line & time <= td_delay_line+Tpd(wf));
    time = time(good_rbins);
    mean_data = mean_data(good_rbins);
    
    mean_data = mean_data - median(mean_data);
    mean_data = mean_data .* exp(-j*2*pi*fc*time);
    [B,A] = butter(4,0.15);
    mean_data = filtfilt(B,A,mean_data);
    
    figure(wf+100*adc); clf;
    set(wf+100*adc,'WindowStyle','docked');
    plot(time*1e6,abs(mean_data));
    grid on;
    title(sprintf('envelope for adc %d wf %d', adc, wf));
    xlabel('time (us)');
    ylabel('relative envelope (V)')
    fig_pos = get(wf+100*adc,'Position');
    set(wf+100*adc,'Position',[fig_pos(1:2) 827 362]);
    
    Nt_xcorr = 2*length(mean_data) - 1;
    time_xcorr = -Tpd(wf) + dt*(0:Nt_xcorr-1).';
    ideal_data = exp(j*2*pi*(f0-fc)*(time-td_delay_line) + j*pi*alpha*(time-td_delay_line).^2) .* rectpuls((time-td_delay_line-Tpd(wf)/2)/Tpd(wf)) * max(mean_data);
    good_rbins = find(time >= td_delay_line & time <= td_delay_line+Tpd(wf));
    ideal_data(good_rbins) = ideal_data(good_rbins) .* tukeywin(length(good_rbins),0.2);
    
    figure(10+wf+100*adc); clf;
    set(10+wf+100*adc,'WindowStyle','docked');
    plot(time_xcorr*1e6, lp(xcorr(mean_data,mean_data)));
    hold on;
    plot(time_xcorr*1e6, lp(xcorr(ideal_data,ideal_data)),'r');
    hold off;
    ylim([-100 0] + max(lp(xcorr(mean_data,mean_data))));
    grid on;
    title(sprintf('xcorr for adc %d wf %d', adc, wf));
    xlabel('time (us)');
    ylabel('relative power (dB)')
    fig_pos = get(10+wf+100*adc,'Position');
    set(10+wf+100*adc,'Position',[fig_pos(1:2) 827 362]);
    
    legend('measured xcorr','ideal xcorr');
  end
end

return;
