% Scan length of rf flat_top on ACC67 to measure the detuning curves


% First take a reference
flattop_name = 'TTF2.RF/LLRF.CONTROLLER/MAIN.ACC67/PULSE_FLATTOP';
det_name =  'TTF2.RF/PIEZO.CALCULATION/C1.ACC6/DETN.TD';

values = [800:-20:20];

initial_value = ttfr(flattop_name);
fprintf('Initial value: %d\n',initial_value);

tstart = now;

for n = 1:length(values)
    this_value = values(n);
    put_times(n) = now;
    fprintf('Time: %s\n',datestr(put_times(n)));
    fprintf('Putting value: %d\n',this_value);
    err = ttfw(this_value,flattop_name);
    if err,
       fprintf('Error in ttfw... %s\n',err)
        fprintf('waiting for user....\n');
       pause
    end
    pause(1)
    % Now collect the detuning waveforms, which aren't in the daq
    fprintf('Reading detuning waveforms...\n');
    det_wf6{n} = doocs_read('TTF2.RF/PIEZO.CALCULATION/C[1;2;3;4;5;6;7;8].ACC6/DETN.TD');
    det_wf7{n} = doocs_read('TTF2.RF/PIEZO.CALCULATION/C[1;2;3;4;5;6;7;8].ACC7/DETN.TD');
    fprintf('Pausing...\n')
    pause(3)
    
end

% restore original value
fprintf('Restoring initial value...\n');
err = ttfw(initial_value,flattop_name);

tend = now;

fnam = strcat('flattop_scan_',datestr(tstart,30));
fprintf('Saving to %s.mat ...\n',fnam);
eval(['save data/',fnam])
