function A = airlight(HazeImg, DarkImg, method)
% estimating the global airlight

if strcmp(method, 'method1')
    A = min(240, max(max(DarkImg)));
elseif strcmp(method, 'method2')
    A = airlight_He(HazeImg, DarkImg);    
elseif strcmp(method, 'method3')
    A = airlight_Kim(DarkImg);
else
    error('parameter error.');
end

end

function A = airlight_He(HazeImg, DarkImg)
% estimating the global airlight using He's method

% the top 0.1% brightest pixels in the dark channel
topDark = sort(DarkImg(:), 'descend');
coord_bound = round(0.001 * length(topDark));    
value_bound= topDark(coord_bound);                      
coord = find(DarkImg >= value_bound); 
 
% the brightest pixels in the grayimage
GrayImg = rgb2gray(HazeImg);
Bright = GrayImg(coord);
Brightest = find(Bright == max(Bright));
coord_A = coord(Brightest); 
coord_A = coord_A(1);
A = DarkImg(coord_A);

end

function A = airlight_Kim(DarkImg)
% estimating the global airlight using Kim's method
thres = 50;
score = 0;
[height, width] = size(DarkImg);
if max(height, width) <= thres
    A = min(240, max(max(DarkImg)));
else
    Image = DarkImg(1:floor(height / 2),1:floor(width / 2));
    num = floor(height / 2) * floor(width / 2);
    average = mean(mean(Image));
    deviation = sqrt(sum(sum((Image - average).^2)) / num);
    if average - deviation > score
        score = average - deviation;
        Image_temp = Image;
    end

    Image = DarkImg(1:floor(height / 2),floor(width / 2) + 1:width);
    num = floor(height / 2) * (width - floor(width / 2));
    average = mean(mean(Image));
    deviation = sqrt(sum(sum((Image - average).^2)) / num);
    if average - deviation > score
        score = average - deviation;
        Image_temp = Image;
    end

    Image = DarkImg(floor(height / 2) + 1:height,1:floor(width / 2));
    num = (height - floor(height / 2)) * floor(width / 2);
    average = mean(mean(Image));
    deviation = sqrt(sum(sum((Image - average).^2)) / num);
    if average - deviation > score
        score = average - deviation;
        Image_temp = Image;
    end

    Image = DarkImg(floor(height / 2) + 1:height,floor(width / 2) + 1:width);
    num = (height - floor(height / 2)) * (width - floor(width / 2));
    average = mean(mean(Image));
    deviation = sqrt(sum(sum((Image - average).^2)) / num);
    if average - deviation > score
        score = average - deviation;
        Image_temp = Image;
    end
    
    A = airlight_Kim(Image_temp);
end

end

