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

function [M1, M2, D] = save_waveforms_v3(usb, keys, initialization_data)

    % 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;
    
    %Pocet mereni je 256, protoze se meni pouze 1. bajt od 0 do 255.
    n_measures = 256;
    
    %Priprava ACK pro potvrzeni, ze prubeh byl zaznamenan.
    ACK = uint8([2 1 255 255]);
    
    % Priprava klice pro odeslani.
    key = key_preparation(keys);

    % Priprava dat, pozdeji se meni pouze 1. bajt.
    first_byte_data = initialization_data;
    
    % Odeslani klice.
    transmit(key);
    pause(0.5);

    % Smycka pro mereni X prubehu.
    for i = 1 : n_measures
        % Vygenerovani dat o velikosti 16 bajtu.
        first_byte_data(1) = i - 1;
        D(i,:) = first_byte_data;
        %D(i,:) = initialization_data;

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

        %for j = 1 : 5
            % Execute device object function(s).
            ctr = ctr+1;
            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;
            pause(0.1);
       %end
        
        % Potvrzeni, ze prubehy byly zmereny.
        transmit(ACK);
        pause(0.2);     
    end

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