
%% FUNCTION "startFiltering": 
%% Deletes duplicate rows within a 100-millisecond range 
%% based on the Start time

function startFiltering
    % File path for .mat files
    [filePaths, ~, ~] = getFileonAllCell('Select label files', 'mat');

    % Folder path to save the results
    savePath = uigetdir('Select the folder to save the results');
    
    % Main loop
    for i = 1:length(filePaths)
        % Loading the file
        load(filePaths{i}, 'detectionRows');
        
        % Checking if 'detectionRows' exists 
        % in the loaded file
        if exist('detectionRows', 'var')
            
            % Sorting the rows by the time displayed 
            % in the Start column
            detectionRows = sortrows(detectionRows, 'Start');
            
            % Iterating through each row in 'detectionRows'
            rowToDelete = [];

            for j = 1:height(detectionRows)
                % Finding rows with time within 
                % 100 milliseconds range
                timeRangeRows = find(abs(detectionRows.Start - ...
                    detectionRows.Start(j)) <= milliseconds(100));
                
                % Excluding the current row itself from deletion
                timeRangeRows = setdiff(timeRangeRows, j);
                
                % Accumulating rows to delete
                rowToDelete = [rowToDelete; timeRangeRows];
            end
            
            % Deleting duplicate rows within the time range
            detectionRows(rowToDelete, :) = [];
            
            % Sorting the rows by the time displayed 
            % in the Start column again
            detectionRows = sortrows(detectionRows, 'Start');
            
            [~, name, ext] = fileparts(filePaths{i});
            save(fullfile(savePath, [name '_start' ext]), 'detectionRows');
        else
            % Displaying a warning if 'detectionRows' 
            % is not found in the file
            warning(['detectionRows not found in file: ' filePaths{i}]);
        end
    end
end



%% FUNCTION "getFileonAllCell": 
%% Gets file paths for .mat files
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [filepn, filep, filen] = getFileonAllCell(prompt, ext)
    loadpath = 'C:\Users\Kudlacek\Documents\Experiment\Matlab';
    
    if exist('startpath.mat', 'file')
        load('startpath.mat', 'loadpath');
    end
    
    [filen, filep] = uigetfile([loadpath '.' ext], prompt, 'MultiSelect', 'on');
    
    if ischar(filep)
        loadpath = filep;
        
        if exist('startpath.mat', 'file')
            save('startpath.mat', 'loadpath', '-append');
        else
            save('startpath.mat', 'loadpath');
        end
    end
    
    filepn = fullfile(filep, filen);
    
    if ~iscell(filepn) && ~iscell(filep) && ~iscell(filen)
        a{1} = filepn;
        b{1} = filep;
        c{1} = filen;
        clear filepn filep filen
        filepn = a;
        filep = b;
        filen = c;
    end
end