function LRTSSV_VisualizeTracks(processedDataFolder,frameRange,showParticleTracks,showParticleDetections, imageType)
% LRTSSV_VisualizeTracks - Overlays SPC and LPC particles and tracking trajectories on image frames.
%
%   This function reads image frames from the processed experiment folder
%   and overlays particle detections and tracking trajectories from both SPC and LPC cameras.
%
%   INPUTS:
%       processedDataFolder    (string)  - Directory containing processed experiment results.
%       frameRange             (int 1x2) - Specify starting and ending index of frames ([1 inf] for all frames).
%       showParticleTracks     (bool)    - Plot particle tracking trajectories
%       showParticleDetections (bool)    - Highlight all detected particles (tracked or not)
%       imageType              (string)  - Type of processed image for overlays, options are: 
%                                           'Denoised', 'Binary', 'Particle'
%
%   Example Usage:
%       visualizeTracks_UChi('\Exp59-20250909_150000\PROCESSED DATA', [1 inf], 1, 1, 'Denoised');
%
%% Get Images
% Define image folder paths for SPC and LPC

if strcmpi(imageType,'DENOISED')
    imageDir = 'DENOISED IMAGES';
elseif strcmpi(imageType,'BINARY')
    imageDir = 'BINARY IMAGES';
elseif strcmpi(imageType,'PARTICLE')
    imageDir = 'PARTICLE IMAGES';
else
    error('ImageType not recongized, options are: ''DENOISED'', ''BINARY'', ''PARTICLE''');
end

imageFolder_SPC = dir(fullfile(processedDataFolder, 'PROCESSED IMAGES', imageDir, '*', 'SPC_*'));
imageFolder_SPC = fullfile(imageFolder_SPC.folder,imageFolder_SPC.name);
imageFolder_LPC = dir(fullfile(processedDataFolder, 'PROCESSED IMAGES', imageDir, '*', 'LPC_*'));
imageFolder_LPC = fullfile(imageFolder_LPC.folder,imageFolder_LPC.name);

% Get sorted image file lists for SPC and LPC
imageFiles_SPC = dir(fullfile(imageFolder_SPC, '*.tiff'));
imageFiles_LPC = dir(fullfile(imageFolder_LPC, '*.tiff'));

% Ensure both image folders exist
if ~isfolder(imageFolder_SPC) || ~isfolder(imageFolder_LPC)
    error('One or both image folders not found: %s | %s', imageFolder_SPC, imageFolder_LPC);
end

% Sort file lists by name
[~, sortIdx_SPC] = sort({imageFiles_SPC.name});
imageFiles_SPC = imageFiles_SPC(sortIdx_SPC);

[~, sortIdx_LPC] = sort({imageFiles_LPC.name});
imageFiles_LPC = imageFiles_LPC(sortIdx_LPC);


%% Load Tracks .mat File
tracksFile = dir(fullfile(processedDataFolder,'Tracking Data','*tracking_data_raw.mat'));
if isempty(tracksFile)
    error('Tracks .mat file not found in %s', ProcessedDataFolder);
end
tracksMATFile  = load(fullfile(tracksFile.folder,tracksFile.name));

% Extract SPC and LPC tracks
particleTracks_SPC = tracksMATFile.tracksData.tracksData_SPC;
particleTracks_LPC = tracksMATFile.tracksData.tracksData_LPC;

if isfield(tracksMATFile.tracksData,'frameRange')
    frameRangeActual = tracksMATFile.tracksData.frameRange;
else
    frameRangeActual = [1 length(imageFiles_LPC)];
end

%% Load Particle .mat file

particlesFile = dir(fullfile(processedDataFolder,'Particle Data','*particle_data_raw.mat'));
if isempty(particlesFile)
    error('Particle .mat file not found in %s', ProcessedDataFolder);
end
particleMATFile  = load(fullfile(particlesFile.folder,particlesFile.name));

% Extract SPC and LPC particle detection data
particleData_SPC = particleMATFile.particleData.particleData_SPC;
particleData_LPC = particleMATFile.particleData.particleData_LPC;

%% Loop Through Images

% Create figure with tiled layout for side-by-side comparison
figure(1);clf;set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
set(groot,'defaultAxesTickLabelInterpreter','latex','defaulttextinterpreter','latex','defaultLegendInterpreter','latex');
set(gcf, 'Color', 'w');
tiledlayout(1,2, 'Padding', 'compact', 'TileSpacing', 'compact');

% Loop through frames, displaying SPC on the left and LPC on the right
for iFrame = frameRangeActual(1):frameRangeActual(2)
    
    imgIndex = iFrame - frameRangeActual(1) + 1;
    
    if imgIndex < frameRange(1) || imgIndex > frameRange(2)
        continue
    end
    
    % Read SPC and LPC images
    imgPath_SPC = fullfile(imageFolder_SPC, imageFiles_SPC(imgIndex).name);
    imgPath_LPC = fullfile(imageFolder_LPC, imageFiles_LPC(imgIndex).name);
    img_SPC = imread(imgPath_SPC);
    img_LPC = imread(imgPath_LPC);
    
    % --- Plot SPC (Left) ---
    nexttile(1);
    imshow(img_SPC);
    hold on;
    title(sprintf('SPC - Actual Exp. Frame %d', iFrame),'interpreter','latex','FontSize',20);
    
    % Plot tracks
    if (showParticleTracks)
        for k = 1:numel(particleTracks_SPC)
            trackFrames = particleTracks_SPC(k).fn;
            if any(trackFrames == iFrame)
                idx = trackFrames <= iFrame;
                trackX = particleTracks_SPC(k).x(idx);
                trackY = particleTracks_SPC(k).y(idx);
                plot(trackX, trackY, 'r-', 'LineWidth', 2);
                plot(trackX(end), trackY(end), 'r+', 'MarkerSize', 10, 'LineWidth', 2);
            end
        end
    end
    
    % Plot detected particles from particleData (contains both tracked and untracked particles)
    if (showParticleDetections)
        frameMask_SPC = particleData_SPC.fn == iFrame;
        if any(frameMask_SPC)
            frameX_SPC = particleData_SPC.x(frameMask_SPC);
            frameY_SPC = particleData_SPC.y(frameMask_SPC);
            frameAED_SPC = particleData_SPC.aed(frameMask_SPC);
            
            % Use scatter to visualize particles with size proportional to area-equivalent diameter
            scatter(frameX_SPC, frameY_SPC, frameAED_SPC*2, 'go', 'LineWidth', 1.5);
        end
    end
    
    
    hold off;
    
    % --- Plot LPC (Right) ---
    nexttile(2);
    imshow(img_LPC);
    hold on;
    title(sprintf('LPC - Actual Exp. Frame %d', iFrame),'interpreter','latex','FontSize',20);
    
    % Plot tracks
    if (showParticleTracks)
        for k = 1:numel(particleTracks_LPC)
            trackFrames = particleTracks_LPC(k).fn;
            if any(trackFrames == iFrame)
                idx = trackFrames <= iFrame;
                trackX = particleTracks_LPC(k).x(idx);
                trackY = particleTracks_LPC(k).y(idx);
                plot(trackX, trackY, 'r-', 'LineWidth', 2);
                plot(trackX(end), trackY(end), 'r+', 'MarkerSize', 10, 'LineWidth', 2);
            end
        end
    end
    
    % Plot detected particles from particleData (contains both tracked and untracked particles)
    if (showParticleDetections)
        frameMask_LPC = particleData_LPC.fn == iFrame;
        if any(frameMask_LPC)
            frameX_LPC = particleData_LPC.x(frameMask_LPC);
            frameY_LPC = particleData_LPC.y(frameMask_LPC);
            frameAED_LPC = particleData_LPC.aed(frameMask_LPC);
            
            % Use scatter to visualize particles with size proportional to area-equivalent diameter
            scatter(frameX_LPC, frameY_LPC, frameAED_LPC*2, 'go', 'LineWidth', 1.5);
        end
    end
    
    hold off;
    
    drawnow;
    %pause(0.05); % Adjust visualization speed
end

end
