function [gamma]=searchgamma(I,mask,DF,params,nsearch,numitr)
%--------------------------------------------------------------------------
% [1]  Joy A, Paul J S. "Multi-channel MR Image Reconstruction using
%      Statistically Optimized Non-Linear Diffusion", Magnetic Resonance in 
%      Medicine, June 2017, doi:10.1002/mrm.26774.
% Email: ajin.joy@iiitmk.ac.in, j.paul@iiitmk.ac.in
%
% Coded by : Ajin Joy on March 2017
%--------------------------------------------------------------------------
minsearch     = 0;
maxsearch     = max(abs(I(:)));
params.numitr = numitr; % number of iterations per search
fprintf('searching gamma.. max %d searches (%d iterations per search)\n',nsearch,numitr);
for i=1:nsearch
    fprintf('Searches completed: %d\n',i-1);
    mid          = minsearch/2 + maxsearch/2;
    params.gamma = minsearch/2 + mid/2;
    Outmin       = NLdiffusionMRI_stripped(I,mask,DF,params);
    params.gamma = mid/2 + maxsearch/2;
    Outmax       = NLdiffusionMRI_stripped(I,mask,DF,params);
    if abs(Outmin.err(end)-Outmax.err(end))<1e-4
        params.gamma = mid;
        fprintf('Found gamma in %d searches.\n',i);
%         if Outmin.err(end)<Outmax.err(end),
%             params.gamma = minsearch/2 + mid/2;
%         end
        break;
    end
    if Outmin.err(end)<Outmax.err(end)
        maxsearch = minsearch/2 + maxsearch/2;
    else
        minsearch = minsearch/2 + maxsearch/2;
    end
    fprintf(repmat('\b',1,21+numel(num2str(i-1))));
end
gamma = params.gamma;