function img2=tz_maskimg_3d(img,maskimg)
%TZ_MASKIMG_3D Crop 3D image by an mask.
%   IMG2 = TZ_MASKIMG_3D(IMG,MASKIMG)
%   
%   See also

%   17-Sep-2005 Initial write T. Zhao
%   Copyright (c) Murphy Lab, Carnegie Mellon University

%function img2=tz_maskimg_3d(img,maskimg)
%
%OVERVIEW:
%   Creates a maskimg with the same z dimension as img and uses it to mask
%   the original image.
%
%Edited:
%D. Sullivan 6/6/13 added support for 3D masks and catch/override for
%                   multiple masks being passed at once.
%
%%%%%%

nslice=size(img,3);
%D. Sulliavn 6/6/13 allow for 3D masks with the same size as the original
%image
if size(maskimg,3)~=nslice
    %D. Sullivan 6/6/13 force the mask without the same number of
    %slices to be 2D to start. otherwise take the first non-zero slice
    useslice = find(squeeze(sum(sum(maskimg,1),2)),1);
    if size(maskimg,3)>1
         warning(['Number of mask slices>1&&not equal to number of',...
             'image slices Using first non-zero mask channel.',...
             ' If multiple are cells present, please save each as a ',...
             'separate file with its own mask.']);
    end
    
    img2 = zeros(size(img));
    %D. Sullivan 6/6/13 get rid of for loop in favor of repmat for speed.
    %make sure the mask is 0's and 1's (could have been 0,255 or something)
    maskimg = repmat(maskimg(:,:,useslice),[1,1,nslice])>0;
    img2 = img.*maskimg;
%     for i=1:nslice
%         simg=img(:,:,i);
%         %D. Sullivan 6/6/13 handle case where maskimg has multiple slices
%         %     simg(find(maskimg==0))=0;
%         simg(find(maskimg(:,:,useslice)==0))=0;
%         img2(:,:,i)=simg;
%     end
else
    %D. Sullivan 6/6/13 again, no need for a for loop
    %make sure the mask is 0's and 1's (could have been 0,255 or something)
    img2 = (maskimg>0).*img;
end

