function [InsideOrOutsideGranules, MeanLengthInsideCounter] = ...
    AllCoords_DwellTimeSpent(ScriptVar, AllCoords, RequiredFrames)
    % Calculate dwell time of particles in viscous granules
    % Outputs -
    %    InsideOrOutsideGranules - m x n array of 1's and 0's; m = total number of particles, n
    %                              = number of frames; 1 => particle inside granule, 0 =>
    %                              not inside granule
    %    MeanLengthInsideCounter - m x 1 array where m = total number of
    %                              particles; take mean, SEM for dwell time
    %                              information
    % 
    % Inputs - 
    %    ScriptVar - Parameters container map
    %    AllCoords - Array of particle coordinates 
    %    RequiredFrames - 1 x 2 array of start and end frames
    %
    % Example -
    %    [abc, xyz] = AllCoords_DwellTimeSpent(ScriptVar, AllCoords, [100 525])
    
    tic
    N_Particles_sampled = 10000;
    TotalParticles = sum(ScriptVar('N_Particles'));
    if ~exist('RequiredFrames','var')
        RequiredFrames = [1 ScriptVar('N_Frames')];
    end
    TotalFrames = RequiredFrames(2)-RequiredFrames(1)+1;
    AllCoords = AllCoords(randperm(TotalParticles,N_Particles_sampled)',:,:);
    InsideOrOutsideGranules = zeros(N_Particles_sampled, TotalFrames);
    MeanLengthInsideCounter = zeros(N_Particles_sampled,1); 
    LengthInsideCounter = zeros(N_Particles_sampled, TotalFrames);
    for i = 1:N_Particles_sampled
        InsideOrOutsideGranules(i,:) = reshape(AllCoords(i,3,:),[1 TotalFrames]);
        if ~mod(i,1000)
            fprintf("Particle %d completed\n",i)
            toc
        end
        ContiguousOnesCounter = 0;
        k = 1;
        for j = 1:TotalFrames
            if InsideOrOutsideGranules(i,j) == 1
                ContiguousOnesCounter = ContiguousOnesCounter + 1;
            end
            if InsideOrOutsideGranules(i,j) == 0 || j == TotalFrames
                if ContiguousOnesCounter > 0
                    LengthInsideCounter(i,k) = ContiguousOnesCounter;
                    k = k + 1;
                    ContiguousOnesCounter = 0;
                end
            end
        end
        MeanLengthInsideCounter(i,1) = mean(nonzeros(LengthInsideCounter(i,:)));
    end
    fprintf("\n********\nDwell time function completed\n********\n")
    toc
end