% function normaliseImagesToVoxelSize
% function normaliseImagesToVoxelSize
%
% Utility script to resize images in current directory to reflect a
% predefined voxel size. The images are assumed to have the voxel size in
% the file name following the format used for volume directory names.
% Motivation is to resize screenshots taken from viewVolume to have them to
% scale. Note that viewVolume normalises to the smallest voxel size on
% display, hence we use the minima to work out scaling. 
% Note that we assume 3 character extensions. Also not that we have only
% used this for cubic voxel sizes from OPT screenshots, hence the minimum
% dimension is the voxel size in x, y and z

% targetVoxelSize = [13.11, 13.11, 13.11];
% targetVoxelSize = [52.44, 52.44, 52.44];
targetVoxelSize = [34.94, 34.94, 34.94];
minTargetVoxelSizeDim = min(targetVoxelSize);

imageFormat = 'png';
files = dir;

for i = 1:length(files)
    f = files(i);

    if ~f.isdir && strcmp(f.name(end - 2:end), imageFormat);
        % Load image
        image = imread(f.name);

        % Get the file name without the extension
        imageFileNameNoExt = f.name(1:end-4);
        
        % Get the voxel size
        [imageVoxelSize, found, imageVoxelSizeString] = ...
            getVoxelSizeFromString('String', imageFileNameNoExt);
        
        % Find minimum voxel size dimension and compare to minimum target
        % voxel size dimension
        minImageVoxelSizeDim = min(imageVoxelSize);
               
        factor = minImageVoxelSizeDim / minTargetVoxelSizeDim;
        resizedImageVoxelSize = imageVoxelSize / factor;
        
        scaledImage = imresize(image, factor);
        
        
         % Determine new name
         precision = 3;
         format = '%350.2f'; % Fieldwidth of 350 - 2 decimal places allows for realmax('double') value
         resizedImageVoxelSizeStr = ['x', num2str(resizedImageVoxelSize(1), format), 'y', num2str(resizedImageVoxelSize(2), format), 'z', num2str(resizedImageVoxelSize(3), format)];
         resizedImageVoxelSizeStr = regexprep(resizedImageVoxelSizeStr, '\.', 'p');
         resizedImageNameNoExt = regexprep(imageFileNameNoExt, imageVoxelSizeString, resizedImageVoxelSizeStr);


        scaledImageFileNameNoExt = [resizedImageNameNoExt, '_scaled.', imageFormat];
        imwrite(scaledImage, scaledImageFileNameNoExt, imageFormat); 
    end
end

