function createMembraneMask(im,filename,savedir,membranethickness)
% This function takes in an image im and generates a series of masks 
% for isolating the membrane - later used for calculating FRET
% im: 2D grey image to threshold
% membranethickness: input for masking
% filename: filename to save the resulting masks
% savedir: directory where filename should be saved
% file will have following variables:
    % im: 2D double grey valued image
    % ThickMembraneMask: 2D binary mask of thick crude membrane mask
    % CytoMask: 2D binary mask of the cytosol'
    % MaskFullCell: 2D binary mask of thresholde of full cell
    % MembraneMask: resulting membranemask
    % params: structure with all parameters used to calculate masks
if nargin<4
    membranethickness = 20;
end
%-- input params
params.erosionPar1 = 40;
params.erosionPar2 = 40;
params.MinPix = 1000;
params.thresholdParameter = Inf;
params.fillholes = 2;
params.membranethickness = membranethickness;

%--- find crude mask 
[out,~] = threshold(im,'isodata',params.thresholdParameter);  
out2=berosion(bdilation(out,params.erosionPar1),params.erosionPar2);    
CM=fillholes(out2,params.fillholes);
%get rid of small objects
LI=label(CM);
for ii=1:max(LI)
   if sum(LI==ii)<params.MinPix
       LI(LI==ii)=0;
   end
end
Mask=LI>0;
DTim=dt(Mask);  
%now do distance transform
ThickMembraneMask = (DTim<params.membranethickness)&(DTim>0);

%--- get cytosolic mask
FullCellMask = threshold(im,'isodata',params.thresholdParameter);
CytoMask = FullCellMask - ThickMembraneMask;

%--- make membrane mask
MembraneMask = FullCellMask - CytoMask;
FinalMembrane = im.*MembraneMask;

%--- save results
save(fullfile(savedir,filename),'im','FinalMembrane','MembraneMask','CytoMask','FullCellMask','ThickMembraneMask','Closed_Mask','params');
% png files:
% --original image
dip_image(im)
saveas(gcf,fullfile(savedir,[filename '_image']),'png');
close(gcf);
% --membrane mask over original image
overlay(im,MembraneMask)
saveas(gcf,fullfile(savedir,[filename '_overlay']),'png');
close(gcf);
% -- final membrane
FinalMembrane
saveas(gcf,fullfile(savedir,[filename '_FinalMembrane']),'png');
close(gcf);
% --FullCellMask
FullCellMask
saveas(gcf,fullfile(savedir,[filename '_FullCellMask']),'png');
close(gcf);
% --Membrane Mask 
MembraneMask
saveas(gcf,fullfile(savedir,[filename '_MembraneMask']),'png');
close(gcf);
% --Cyto Mask
CytoMask
saveas(gcf,fullfile(savedir,[filename '_CytoMask']),'png');
close(gcf);
% --ThickMembrane Mask 
ThickMembraneMask
saveas(gcf,fullfile(savedir,[filename '_ThickMembrane']),'png');
close(gcf);
% --Closed_Mask 
Closed_Mask
saveas(gcf,fullfile(savedir,[filename '_ClosedMask']),'png');
close(gcf);
end







