% Base directory containing masked_T1, masked_T2, ..., masked_T80 folders
baseDir = 'export/Upsampled_results/full_tomo/'; % Update this path

% Number of bins and their range
numBins = 256;
binRange = [0, 10000];

% Preallocate the histogram matrix
histMatrix = zeros(numBins, 218); % 80 stacks

% Define the bin edges for the histogram
binEdges = linspace(binRange(1), binRange(2), numBins+1);

% Process each stack
for i_tframes = 1:24
    fprintf('Processing masked_T%d\n', i_tframes);
    
    % Folder for the current stack
    folderName = sprintf('Upsampled_T%d', i_tframes);
    folderPath = fullfile(baseDir, folderName);
    
    % Initialize a temporary array to hold the histogram counts for this stack
    stackHistCounts = zeros(numBins, 1);
    
    % Process each slice of the stack
    for sliceIndex = 2:64
        % Construct the slice filename and path
        imageName = sprintf('masked_S%02d.tif', sliceIndex);
        imagePath = fullfile(folderPath, imageName);
        
        % Read the slice
        sliceData = imread(imagePath);
        
        % Update the histogram counts for this stack
        sliceHistCounts = histcounts(sliceData, binEdges);
        stackHistCounts = stackHistCounts + sliceHistCounts(:);
    end
    
    % Store the histogram counts for this stack in the matrix
    histMatrix(:, i_tframes) = stackHistCounts;
end

% Bin centers for the histogram
binCenters = (binEdges(1:end-1) + binEdges(2:end)) / 2;

% Combine bin centers and histogram counts
outputMatrix = [binCenters', histMatrix];

% Write to a text file
outputFilePath = fullfile(baseDir, 'histogram_data_1_24tp.txt');
writematrix(outputMatrix, outputFilePath, 'Delimiter', 'tab');

fprintf('Histogram analysis completed and saved to "%s".\n', outputFilePath);