function [Objects,refinedmask] = segment_fromImage_refinedWS(img, par)

sigma = par(1);    %sigma of the gaussian blurring of the image
minSize = par(2);  %minimum size of the objects for the BLUE image
factor_rough = par(3);   %for the rough thresholding.
factor_fine = par(4);   %for the fine thresholding.
maxSize=par(5);    %maximum size of the objects for the BLUE image

% Blur roughly the  image
    FilterImg = imfilter(img,fspecial('gaussian', 20,  7),'same');

% Threshold the image
    levelTr = factor_rough*graythresh(FilterImg);
     ThrImg = im2bw (FilterImg, levelTr);
  
% Exclude the small objects in the  thresholded image
    ThrImg = imfill(ThrImg,'holes'); % fill holes
    ThrImg = bwareaopen(ThrImg,minSize);
    
    
% Get the objects thresholded 

    ObjectsProv=segment_fromMask(ThrImg, [0.5*minSize,1.5*maxSize]);    %Notice that for the provisory objects we are more loose about the cells considered
    LabelsMapProv=labelmatrix(ObjectsProv);   
    BoundingBox = regionprops(LabelsMapProv,'BoundingBox');  
    
    refinedmask=zeros(size(LabelsMapProv));   
    doubleimg=double(img);
    
    if sigma>0
    doubleimg=imfilter(doubleimg,fspecial('gaussian', 20,sigma),'same');
    end;

%We apply now a threshold applied for the mean in each object. 
    
for n=1:size(BoundingBox)
        Boundingcell=BoundingBox(n).BoundingBox;
        smallmat=doubleimg(ceil(Boundingcell(2)): floor(Boundingcell(2)+Boundingcell(4)), ceil(Boundingcell(1)): floor(Boundingcell(1)+Boundingcell(3)));
        matrixprov=zeros(size(LabelsMapProv));
        matrixprov(ceil(Boundingcell(2)): floor(Boundingcell(2)+Boundingcell(4)), ceil(Boundingcell(1)): floor(Boundingcell(1)+Boundingcell(3)))=1;            
        threshprov=factor_fine*mean(smallmat(:));
        refinedmask=or(refinedmask,((matrixprov.*doubleimg)>threshprov));
             
 end;
       

refinedmask=refinedmask.*(LabelsMapProv>0); 

DistImg = -bwdist(~refinedmask);  %lower values in the center of the objects
dummy = imextendedmin(DistImg,2); %Search the minima and somehow expands them
DistImg = imimposemin(DistImg,dummy); %Modifies the image so the local minima are only where dummy is nonzero
WSHD = watershed(DistImg); %Watershedregions are the basin for the minima, all having the same value
refinedmask(WSHD == 0) = 0; %This is to identify the boundaries between basins for the watershed.
refinedmask=imfill(refinedmask,'holes');
refinedmask = xor(bwareaopen(refinedmask,minSize),bwareaopen(refinedmask,maxSize));
Objects = bwconncomp(refinedmask);


end

