function [Error_Number,Error_Message] = AWG4k_System_Error(obj,Display_Error)
%[Error_Number,Error_Message]=AWG4k_System_Error(obj,Display_Error);
%
%This function queries the instrument for errors. It continues to query
%until it receive "0, No Error". The Error Number and the Error Message are
%returned respectively as numeric array and as cell array.
%The input parameters are:
%- obj: VISA object.
%- Display_Error: 0 or 1. 1 displays error messages from AWG.
%
%The output parameters are:
%- Error_Number: array of error numbers.
%- Error_Message: array of error messages in cell format.
%
%Example: [Err_Num,Err_Msg] = AWG4k_System_Error(obj,1);

err_no=1;
i=1;
%Loop until it receive error number = 0
while err_no~=0
    
    %send the query
    fprintf(obj, 'SYST:ERR?');
    
    %read the response
    message=fscanf(obj);
    
    %save error number and message     
    [err_no,~,~,next_index]=sscanf(message,'%d,');
    Error_Number(i)=err_no;
    Error_Message{i}= message(next_index:end);
    i=i+1;   
end

%display message
if Display_Error > 0
    fprintf('Error Messages:\n');
    for i=1:length(Error_Number)
        fprintf('%d,%s',Error_Number(i),Error_Message{i});
    end
end

end

