% Define paths to the folders containing masks and images
masksFolder = 'export/Upsampled_results/golden_mask_erroded/';
imagesFolder = 'export/Upsampled_results/all_timepoints/raw_64_slices/';
exportFolder = 'export/Upsampled_results/all_timepoints/masked_64_slices/';

% Iterate through each mask
for i = 2 %2:64
    % Load the mask
    maskFilename = sprintf('mask_S%04d.tif', i);
    maskPath = fullfile(masksFolder, maskFilename);
    mask = imread(maskPath);
    
    % Iterate through each image in the corresponding folder
    imagesSubFolder = sprintf('Upsampled_S%d', i);
    imagesFolderPath = fullfile(imagesFolder, imagesSubFolder);
    images = dir(fullfile(imagesFolderPath, '*.tif'));
    
     % Create a folder for the masked images if it doesn't exist
    maskedImagesSubFolder = fullfile(exportFolder, imagesSubFolder);
    if ~exist(maskedImagesSubFolder, 'dir')
        mkdir(maskedImagesSubFolder);
    end  
    
    for j = 1:numel(images)
        % Load the image
        imageFilename = images(j).name;
        imagePath = fullfile(imagesFolderPath, imageFilename);
        image = imread(imagePath);
        
        tempResult = double(image) .* double(mask);
        
        % Clip the result to the int32 range to avoid overflow
        tempResult(tempResult < intmin('int32')) = intmin('int32');
        tempResult(tempResult > intmax('int32')) = intmax('int32');

        % Convert the result back to int32
        maskedImage = int32(tempResult);
        
        % Save the masked image
        maskedImageFilename = sprintf('masked_%s', imageFilename);
        maskedImagePath = fullfile(maskedImagesSubFolder, maskedImageFilename);
        t = Tiff(maskedImagePath,'w');
        tagstruct.ImageLength = size(maskedImage, 1);
        tagstruct.ImageWidth = size(maskedImage, 2);
        tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
        tagstruct.BitsPerSample = 32;
        tagstruct.SamplesPerPixel = 1;
        tagstruct.RowsPerStrip = 16;
        tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
        tagstruct.Software = 'MATLAB';
        tagstruct.SampleFormat = Tiff.SampleFormat.Int; % Specify sample format as integer
        t.setTag(tagstruct);
        t.write(maskedImage);
        t.close();
    end
    fprintf('Processed %s\n', maskFilename);
end

fprintf('All folders have been processed.\n');




