function createMaskForNormalTissue(normalDir,maskDir,resolutionLevel)
% Write bigimage masks to disk at the specified resolution level,
% resolutionLevel for tissue regions in images in the directory normalDir.
% The masks are written to disk at the specified location, maskDir. The
% masks are used during training to read the image blocks containing
% tissue.
%
% The function gets the image at the specified resolution level, converts
% the image to the L*a*b* color space, and performs Otsu thresholding of
% the a* channel.
%
% The Camelyon16 normal training file "normal_144.tif" cannot be read by a
% |bigimage| object, so do not create a mask for this image. 

% Copyright 2019 The MathWorks, Inc.

imds = imageDatastore(normalDir,'FileExtensions',{'.tif'});
for idx = 1:length(imds.Files)
    [~,name] = fileparts(imds.Files{idx});
    
    if strcmp(name,"normal_144")
        continue
    end
    
    maskImageDirName = strcat(name,'_mask');
    if ~exist(fullfile(maskDir,maskImageDirName),'dir')
        im = bigimage(imds.Files{idx});
        ref = setSpatialReferencingForCamelyon16(imds.Files{idx});
        numSpatialDiff = numel(im.SpatialReferencing) - numel(ref);
        im.SpatialReferencing(1:end-numSpatialDiff) = ref;
        
        % Process the full image at specified level. If the resolution
        % level does not fit in memory, then throw an error.
        if resolutionLevel <= 4
            error('Cannot load the image in memory. Specify resolutionLevel greater than or equal to 5.');
        end
        
        I = getFullLevel(im,resolutionLevel);
           
		% Create a mask for normal tissue.
		Ilab = rgb2lab(I);
		A = Ilab(:,:,2);
    
		AScaled = rescale(A);
		AThreshold = imbinarize(AScaled);
    
		se = strel('disk',10);
		mask = imopen(AThreshold,se);
    
		% Make a bigimage out of the image mask and set its spatial reference
		maskImage = bigimage(mask);
		maskImage.SpatialReferencing = im.SpatialReferencing(resolutionLevel);
        
        maskImageDirPathName = fullfile(maskDir,maskImageDirName);
        maskImage = adjustBigImageSize(maskImage,im,resolutionLevel);
        write(maskImage,maskImageDirPathName);
        fprintf('Done with %s\n',name);
    end
end
end