function [outTable] = GroupSpikeTimes(GroupTable, SpikeData)
% GROUPSPIKETIMES Populate an indexed table with associated spike data.
% Required:
%   GroupTable, A table containing labeling information and lists of associated electrodes.
%   SpikeData, A table containing all of the spike times.

    no_g = size(GroupTable, 1);                                 % Find number of groups.
    data_index_e = SpikeData.Electrode;                         % Find the list of electrode names associated with each spike.
    outTable = table();
    for i_g = 1:1:no_g                                              % Loop through each group.
        e_list = GroupTable.Elec_List_Names{i_g};                   %   Find the electrodes associated with the group.
        no_e = size(e_list, 2);                                     %   Find number of electrodes in the list.
        G_Times = cell(1, no_e);                                    %   Create cells to store the spike times.
        G_Mags = cell(1, no_e);                                     %   Create cells to store the spike magnitudes.
        for i_g_e = 1:no_e                                          % Loop through each electrode in the group.
            q_data_i = strcmp(data_index_e, e_list(i_g_e));         %   Find the spikes associated with that group.
            if sum(q_data_i)                                        %   Store the data if there is data present.
                G_Times(i_g_e) = SpikeData.Spike_Times(q_data_i);
                G_Mags(i_g_e) = SpikeData.Spike_Mags(q_data_i);
            end
        end
        
        G_Times = {G_Times};                        % Put the time array into a cell.
        G_Mags = {G_Mags};                          % Put the Magnitude array into a cell.
        outTable(i_g, :) = table(G_Times, G_Mags);  % Store the cells in a table.
    end
    outTable = [GroupTable outTable];           % Add the spike data to the group labelling information.
end
