function [ mask ] =  filterFits(rawFitResults,paramsFilterFits,fitSigma)
% FILTERFITS    filter rawFitResults property to populate FitResults property

%% Filter fits

mask1=(mean(rawFitResults.CRLB_STD,2) <= paramsFilterFits.MaxCRLBSTD) &...
    (mean(rawFitResults.CRLB_STD,2) >= paramsFilterFits.MinCRLBSTD);
fprintf('Eliminated %d localisations based on localization precision\n',sum(~mask1));

[ ~,~,pfa_adj ]=fdr_bh(reshape(rawFitResults.LL(3,:),[prod(size(rawFitResults.LL(3,:))) 1]),min(0.05,paramsFilterFits.MaxPValue),'dep','no');
mask2=(pfa_adj <= paramsFilterFits.MaxPValue);
fprintf('Eliminated %d localisations based on probabilty of false positive\n',sum(~mask2));

mask3=(rawFitResults.Photons <= paramsFilterFits.MaxPhotons) &...
    (rawFitResults.Photons >= paramsFilterFits.MinPhotons);
fprintf('Eliminated %d localisations based on photons\n',sum(~mask3));

mask4=(rawFitResults.Bg <= paramsFilterFits.MaxBg) &...
    (rawFitResults.Bg >= paramsFilterFits.MinBg);
fprintf('Eliminated %d localisations based on bg\n',sum(~mask4));

cds = [rawFitResults.Coord(:,2) rawFitResults.Coord(:,1)]-[rawFitResults.RoiStart(:,2) rawFitResults.RoiStart(:,1)];
% throw away fits if outside fit box
mask5=(cds(:,1)' < size(rawFitResults.ROIStack,1))'&(0 < cds(:,1)')'...
    &(cds(:,2)' < size(rawFitResults.ROIStack,2))'&(0 < cds(:,2)')';

fprintf('Eliminated %d localisations based on location\n',sum(~mask5));
mask = mask1.*mask2.*mask3.*mask4.*mask5;
if nargin >2 && fitSigma
mask6=(rawFitResults.Sigma(:,1) <= paramsFilterFits.MaxSigmax) &...
    (rawFitResults.Sigma(:,1) >= paramsFilterFits.MinSigmax) &...
    (rawFitResults.Sigma(:,2) <= paramsFilterFits.MaxSigmay) &...
    (rawFitResults.Sigma(:,2) >= paramsFilterFits.MinSigmay);
    fprintf('Eliminated %d localisations based on Sigmaxy\n',sum(~mask6));
mask = mask.*mask6;
end

%Write preFitResults
mask7 = ones(size(mask));
if (paramsFilterFits.MinPixelDist > 0)
    coordsCam1=[rawFitResults.Coord rawFitResults.Frame];
   [idx,dist] = knnsearch(coordsCam1.*repmat([1 1 10*paramsFilterFits.MinPixelDist],[size(coordsCam1,1) 1]),coordsCam1.*repmat([1 1 10*paramsFilterFits.MinPixelDist],[size(coordsCam1,1) 1]),'k',2);     
mask7(dist(:,2) <=paramsFilterFits.MinPixelDist)=0;
mask7(idx(dist(:,2) <=paramsFilterFits.MinPixelDist,2))=0;
end
fprintf('Eliminated %d localisations smaller than minPixelDist\n',size(mask,1)-sum(mask7))
mask=mask.*mask7;
mask=logical(mask);