%Determines the optimal threshold for the Fourier coefficients based on
%a distance threshold between 0 (most similar) and 1 (most distant).

%If xslope and yslope are specified, a good threshold will be determined
%using a plane with the given slope as a distance threshold and distThreshold
%as an intercept. Otherwise, we will assume a scalar threshold value.
function [optimal] = determineThreshold(inImg, distThreshold, slope)
    warning('OFF', 'Images:isrgb:obsoleteFunction');

    if (isrgb(inImg))   %isrgb is deprecated? What replaced it?
        inImg = rgb2gray(inImg);
    end
    
    grayImg = im2double(inImg);
    imfft = abs(fft2(grayImg));
    upperbound = max(imfft(:));
    lowerbound = 0;
    
    optimalvector = 0;
    if (nargin >= 4)
        optimalvector = createHighpass(inImg, slope, 0);
    end
    
    %Binary search for the best threshold.
    while (upperbound - lowerbound > 1)
        optimal = (upperbound + lowerbound) / 2;
        if (histogramDistance(grayImg, compressImg(inImg, optimalvector+optimal)) <= distThreshold)
            %The image quality is good; try a higher threshold.
            lowerbound = optimal;
        else
            %The quality is too poor; try a lower threshold.
            upperbound = optimal;
        end
    end
end
