function elektronPriceTableListener(ev,rics)
% elektronPriceTableListener Elektron from Refinitiv example realtime event listener.
%   elektronPriceTableListener(EV,RICS) is an example realtime event listener used
%   to process EMA events.   EV is a four element cell array containing the
%   decoded data, EMA event object, event message and event name.   RICS is
%   the list of securities.
%
%   For example,
%
%   ev =
% 
%   java.lang.Object[]:
% 
%     [ 148   java.util.ArrayList                               ]
%     [1x1 com.thomsonreuters.ema.access.OmmConsumerEventImpl]
%     [1x1 com.thomsonreuters.ema.access.UpdateMsgImpl       ]
%     'AAPL.O'
%  
%   The EMA event object and message inputs can be use to make direct EMA API
%   calls on the event data.
%
%   To run the example,
%
%   e = elektron('mw338','dELEKTRON_DD','111.222.333.444',14002);
%   reqId = realtime(e,'IBM.N',@(~,ev)elektronPriceTableListener(ev,'IBM.N'))
%
%   returns
%
%   reqId = 
% 
%      struct with fields:
%    
%           ReqId: 1
%          ReqMsg: [1x1 com.thomsonreuters.ema.access.ReqMsgImpl]
%          Handle: [1x1 datafeedElektron]
%        Listener: [1x1 handle.listener]
%
%   and in the base workspace, the variable PriceTable will be created.   
%   In this case, PriceTable will contain a single record with the current
%   TRDPRC_1 for IBM.N that is updated in real time.    ReqId is the value 
%   that identifies the data subscription, ReqMsg is the request message 
%   created to initialize the data subscription, Handle is the object that 
%   extends the EMA API listener class, and Listener is the listening object.
%
%   To stop the realtime subscription, 
%
%   delete(reqId.Listener)

%   Copyright 2016-2019 The MathWorks, Inc.

if isempty(ev(2))
  return
end

% Update existing table or create new table if it doesn't exist
if evalin('base', 'exist(''PriceTable'',''var'')')
    priceTable = evalin('base', 'PriceTable');
else
  if ischar(rics) || isstring(rics)
    rics = cellstr(rics);
  end
  priceTable = table(rics(:),zeros(length(rics),1),'VariableNames',{'RIC','TRDPRC_1'});
end

% Convert ArrayList to cell array
eventData = cell(ev(1).toArray);

try
  % Create variable name from event name
  if ~isempty(ev(4))
    
    % 4th input argument is the name associated with the event
    RIC = char(ev(4));
    
    % Get TRD_PRC1 and update table
    i = find(strcmp('TRDPRC_1',eventData));
    if ~isempty(i)
      j = find(strcmp(RIC,priceTable.RIC));
      if ~isempty(j)
        priceTable.TRDPRC_1(j) = eventData{i(1)+2};
      end
    end
  end
  
  assignin('base','PriceTable',priceTable)
  
catch
  % Trap bad message
end

end