
% cd 'E:\00NewMicroscope\TIRF_EPI\'
% cd '/Users/gizemozbaykal/Desktop/MCM/TIRF_EPI/'

dirlist = dir('*-*')
for j = 1:length(dirlist)
    
    fdir = dirlist(j).name
    
    folderList = dir([fdir '/*-*']);
    for i = 1:length(folderList)
        fname = folderList(i).name;
        fileList = dir([fdir  filesep fname filesep 'Pos1/*.tif']);
        AVG = double(imread([fdir filesep fname filesep 'Pos1/' fileList(1).name]));
        for k = 2:length(fileList)
            AVG = AVG + double(imread([fdir filesep fname filesep 'Pos1/' fileList(k).name]));
        end
        AVG = AVG./length(fileList);
        imwrite(uint16(AVG),[fdir filesep fname filesep 'AVG_Pos1.tif'],'tiff')
    end
end

dirlist = dir('*-*')
for i =1:length(dirlist)
fdir = dirlist(i).name

expList = dir([fdir '/GFP*']);

%%
for expId = 1:length(expList)
    
    name01 = [fdir, '/', expList(expId).name, '/']
    
    bild = dir([strrep(name01,'Pos0/',''), 'AVG*']);
    refimgMreB = [strrep(name01,'Pos0/',''),bild(1).name];
    refimg = refimgMreB;

    % Mask for cells
    IMG = double(imread(refimg));
    IMG_vec = reshape(IMG,[],1);
    %figure,imagesc(IMG);
    axis equal

    % Mask for cells
    IMG_vec = reshape(IMG,[],1);

    objS = 10;
    I = zeros(size(IMG)+2*objS);
    I = I +median(IMG_vec);
    I(objS+1:size(IMG,1)+objS, objS+1:size(IMG,2)+objS) = IMG;
    I = mat2gray(I);
    I_vect = reshape(I,[],1);
    saturation = [prctile(I_vect,2) prctile(I_vect,98)];
    I = imadjust(I,saturation); % saturate the lowest and highest vaules (1% each)
    % allow to remove the aberations, e.g. reduce the effect of bubbles
    I = bpass(I,.1,objS,-Inf);

    %I_vect = reshape(I,[],1);
    %saturation = [prctile(I_vect,2) prctile(I_vect,98)]
    %I = imadjust(I,saturation);
    %figure(10),imagesc(IMG.*BW);

    G = fspecial('gaussian', [7 7],3);
    L = imfilter(I,G,'same');
    L = max(L,0); % select only the cell cytoplasms in white (and not the background = 0 and the envelopp < 0
    L = mat2gray(L);
    
    level = graythresh(L);
    BW = im2bw(L, level);
    BW = bwareaopen(BW, 20,8); % remove very little artifacts 
    BW = imdilate(BW,strel('sphere',7)); % dilate to connect the cells by zone
    BW = bwareaopen(BW, 450,8); % remove little (but bigger than the firts removed) artifacts which are not in contact with the cells 
    BW = imdilate(BW,strel('sphere',7)); % continue the dilatation filling the gaps
    BW = BW(objS+1:size(IMG,1)+objS, objS+1:size(IMG,2)+objS);
    BW = 1 - BW;
    BW = bwareaopen(BW, 500,8); % reverse the image to remove the holes at the edges
    BW = 1 - BW;
    BW = imerode(BW,strel('sphere',10)); % erode to get the initial shape (adding 4 pixels corresponding to the envelopp (which initially we didn't select)
    
    test = regionprops(BW, 'Perimeter', 'Area');
    for i = 1: max(max(BW))
        ratio(i) =  test(i).Perimeter / test(i).Area;
        if ratio(i) > 0.35
            BW(BW == i) = 0;
        end
        if max(max(I(BW == i))) < 0.0*max(max(I))
            BW(BW == i) = 0;
        end
    end
    
    %figure,imagesc(BW.*(IMG-0.5)),axis equal, 
    %
    
    nbCells = max(max(BW));
    
    %BW = ones(512,512);
    
    cells = regionprops(BW, 'Orientation', 'MajorAxisLength', 'MinorAxisLength', ...
        'Eccentricity', 'Centroid', 'Area');
    save(['/home/mcm' filesep 'mask'], 'BW', 'cells', 'refimg', 'refimgMreB') % save() doesn't work on atlas
    movefile(['/home/mcm/mask.mat'], [fdir filesep expList(expId).name])
end
end
