function [] = Send_Wfm_Binary_Block(obj,Channel_Number,Waveform)
%[] = Send_Wfm_Binary_Block(obj,Channel_Number,Analog_Waveform)
%
%This function loads a waveform from Matlab workspace to AFG memory using
%the Binary Block.
%The parameters are:
%- obj: VISA object. 
%- Channel_Number: select the channel
%- Analog_Waveform: matrix 1 x N_Samples that contains the analog waveform
%samples.
%
%Example:
% Send_Wfm_Binary_Block(obj,1,Ramp);

%Normalize the samples between 0 and 65535
Wfm_Max = max(Waveform);
Wfm_Min = min(Waveform);

Gain=1;
if Wfm_Max ~= Wfm_Min
    Gain = 65535 / (Wfm_Max - Wfm_Min);
end

Waveform = (Waveform - Wfm_Min) .* Gain;

%Command string
byteCmd = uint8(sprintf('TRACE%d:DATA #',Channel_Number));
CmdLength = length(byteCmd);

%Length of the waveform, each samples take 2 bytes
Wfm_Length = length(Waveform);
LengthByte = 2 * Wfm_Length;

%Measure the length in byte to write in the binary block header
strLengthByte = sprintf('%d',LengthByte);
LengthFieldSize = length(strLengthByte);
strLengthFieldSize = sprintf('%d',length(strLengthByte));

%Allocate an empty vectory of byte
TotalCommandLength = CmdLength + 1 + LengthFieldSize + LengthByte;
ByteArray = zeros(1,TotalCommandLength,'uint8');
        
%Copy the command string
ByteArray(1:CmdLength) = byteCmd;
        
%Write the size of the "Length" field
ByteArray(CmdLength + 1) = uint8(strLengthFieldSize);
        
%Write the Length in byte
ByteArray(CmdLength+2 : CmdLength+2+LengthFieldSize-1) = uint8(strLengthByte);

%Big endian format
MSB = uint8(floor(Waveform / 256));
LSB = uint8(mod(Waveform, 256));

ByteSamples_2xN = vertcat(MSB, LSB);
ByteSamples_1x2N = reshape(ByteSamples_2xN, 1, 2*Wfm_Length);

%Add the waveform data to the byte array to send
ByteArray(CmdLength+2+LengthFieldSize : TotalCommandLength) = ByteSamples_1x2N;

%Send the data to the instrument
fwrite(obj,ByteArray,'uint8');
    
end

