function scouts = add_convhull(scouts)

% Calculate and add coordinates of the convex hull of scouts to the scouts
% structure
%
% INPUT:
%       - scouts (structure): structure with at least the projection field
%       containing the x and y coordinates of the mollweide projection
%       (double matrix) for multiple scouts
%
% OUTPUT:
%       - scouts (structure): same as input structure with an added
%       convhull field containing the x and y coordinates of the convex
%       hulls of each scout
%
%  Written by: Saskia van Heumen, Oktober 2019
%  Written for: Internship at Centre of Pain Medicine, Erasmus MC,
%  Rotterdam

    % Intitalize variance variable
    variance = zeros(length(scouts), 1);
    
    % Calculate the variance in points for every scout
    for i = 1:length(scouts)
        scouts_cor = scouts(i).projection;
        variance(i) = var(scouts_cor(:,1));
    end

    % Check if the variance for every scout is larger than the mean
    % variance, if that is the case the scout is split up in two
    idx_var = find(variance > mean(variance));
    extra = 1;
    
    % Calculate the convex hull for every scout
    for i = 1:length(scouts)
    
        if ismember(i, idx_var) % use kmeans to split a scout up in two groups
            clusters = kmeans(scouts(i).projection, 2);
            scouts_cor1 = scouts(i).projection(clusters == 1, :);
            scouts_cor2 = scouts(i).projection(clusters == 2, :);
            
            if length(scouts_cor1) > 2
                [hull1, ~] = convhull(scouts_cor1);
                scouts(i).convhull = [scouts_cor1(hull1, 1), scouts_cor1(hull1, 2)];
            end

            if length(scouts_cor2) > 2
                [hull2, ~] = convhull(scouts_cor2);
                scouts(length(scouts) + extra) = scouts(i);
                scouts(length(scouts)).convhull = [scouts_cor2(hull2, 1), scouts_cor2(hull2, 2)];
                extra = extra + 1;
            end
        else
            [hull, ~] = convhull(scouts(i).projection);
            scouts(i).convhull = [scouts(i).projection(hull, 1), scouts(i).projection(hull,2)];
        end
    end
        
end


