function [curIdx, vicinityNodeIdxs] = helperBLEMeshChannelMessage(curNode, meshChannel, positions, vicinityRange)
%helperBLEMeshChannelMessage Returns current and its vicinity node indexes
%from Bluetooth mesh channel
%   [CURIDX, VICINITYNODEIDXS] = helperBLEMeshChannelMessage(CURNODE,
%   MESHCHANNEL, POSITIONS, VICINITYRANGE) returns the index of the current
%   node, CURIDX, and list of indexes, VICINITYNODEIDXS, pointing to the
%   messages of vicinity nodes within the range of given node CURNODE, from
%   the given mesh channel, MESHCHANNEL.
%
%   CURIDX (integer) is an index pointing to the given node CURNODE, in
%   mesh channel.
%
%   VICINITYNODEIDXS is a vector representing the list of indexes pointing
%   to the messages of vicinity nodes within the range of given node from
%   mesh channel.
%
%   CURNODE is a unique identifier (positive integer) given to a node
%   within mesh network.
%
%   MESHCHANNEL is a cell-array contains messages transmitted into the
%   channel by each node within the mesh network.
%
%   POSITIONS is an n-by-2 array of node positions within the network.
%
%   VICINITYRANGE is an integer defines the maximum range between the nodes
%   within the network to be visible by other nodes.

%   Copyright 2019 The MathWorks, Inc.

% Initialize
totalNodes = size(meshChannel, 1);
vicinityNodeIdxs = zeros(1, totalNodes);
count = 1;
curIdx = -1;

% Get index of the current node from the channel
for idx = 1:totalNodes
    if (meshChannel{idx, 1}.Identifier == curNode.Identifier)
        curIdx = idx;
    end
end

% Get nodes within the vicinity of "curNode"
vicinityNodes = helperBLEMeshVicinityNodes(curNode.Identifier, ...
    positions, vicinityRange);

% Check for mesh messages from the vicinity nodes
for idx = 1:totalNodes
    % If vicinity node having a message in the channel, then update the
    % values of "vicinityNodeIdxs" and "count"
    if any(vicinityNodes == meshChannel{idx, 1}.Identifier) && ...
        ~isempty(meshChannel{idx, 2})
        % Update vicinity node index of the channel
        vicinityNodeIdxs(count) = idx;
        count = count + 1;
    end
end

% Indexes of the messages within the vicinity of "curNode"
vicinityNodeIdxs = vicinityNodeIdxs(1:count-1);
end
