% M1 je matice pro ulozeni prubehu pri sifrovani.
% M2 je matice pro ulozeni synchronizacniho prubehu.
% D je matice pro ulozeni nahodne vygenerovanych dat.

function save_waveforms(usb, keys, n_measures)

    % Create a VISA-USB object.
    interfaceObj = instrfind('Type', 'visa-usb', 'RsrcName', usb, 'Tag', '');

    % Create the VISA-USB object if it does not exist 
    % otherwise use the object that was found.
    if isempty(interfaceObj)
        interfaceObj = visa('NI', usb);
    else
        fclose(interfaceObj);
        interfaceObj = interfaceObj(1);
    end

    % Create a device object. 
    deviceObj = icdevice('MSO4034.mdd', interfaceObj);

    % Connect device object to hardware.
    connect(deviceObj);
     
    % Nstaveni ulozeni bodu od 1 do 10 0000 / 100 000 / 1 000 000.
    set(deviceObj.Waveform, 'FirstPoint', 1.0);
    set(deviceObj.Waveform, 'EndingPoint', 100000.0);
    
    %Index radku matice prubehu.
    ctr = 0;
    
    %Index matice s prubehy.
    citac = 200;
  
    %Priprava ACK pro potvrzeni, ze prubeh byl zaznamenan.
    ACK = uint8([2 1 255 255]);
    
    % Priprava klice pro odeslani.
    key = key_preparation(keys);

    % Odeslani klice.
    transmit(key);
    pause(0.5);

    % Smycka pro mereni X prubehu.
    for i = 1 : n_measures
        ctr = ctr+1;
        % Vygenerovani dat o velikosti 16 bajtu.
        random_data = data_generator;
        D(ctr,:) = random_data;

        % Priprava dat k odeslani.
        data = data_preparation(random_data);
              
        % Zobrazeni cisla mereni.
        meas = sprintf('Mereni: %s / %s.', num2str(i), num2str(n_measures));
        disp(meas);
        
        % Odeslani dat.
        transmit(data);
        pause(0.5);

            % Execute device object function(s).
            groupObj = get(deviceObj, 'Waveform');
            groupObj = groupObj(1);
            set(deviceObj.Acquisition(1), 'State', 'stop');
            [y1,x1] = invoke(groupObj, 'readwaveform', 'channel1');
            [y2,x2] = invoke(groupObj, 'readwaveform', 'channel2');
            set(deviceObj.Acquisition(1), 'State', 'run');
            M1(ctr,:) = y1;
            M2(ctr,:) = y2;
            
            if mod(ctr, 200) == 0
                data = sprintf('data%s', num2str(citac));
                prubehy = sprintf('traces%s', num2str(citac));
                synchronizace = sprintf('syn%s', num2str(citac));
                assignin('base', data, D);
                assignin('base', prubehy, M1);
                assignin('base', synchronizace, M2);
                citac = citac+200;
                ctr = 0;
            end
            
            pause(0.1);
        
        % Potvrzeni, ze prubehy byly zmereny.
        transmit(ACK);
        pause(0.2);     
    end

    % Odpojeni osciloskopu a smazani objektu.
    disconnect(deviceObj);
    delete(interfaceObj);
  
end