function neighborhood_figure(X, Theta, neighborhood)
% Shows graphically what parameter estimate belongs to a particular neighborhood.
%
% Input arguments:
% X:
%    data set with dimensions [n,N]
% Theta:
%    parameter estimates with dimensions [m,N]
% neighborhood:
%    a cell array vector with a list of neighboring points for each point

% Copyright 2012 Levente Hunyadi

    validateattributes(X, {'numeric'}, {'nonempty','real','2d'});
    validateattributes(Theta, {'numeric'}, {'nonempty','real','2d'});
    validateattributes(neighborhood, {'cell'}, {'nonempty','vector'});

    fig = figure;
    ax = axes('Parent', fig);
    maxfit = 5;  % maximum number of fits
    numfit = 0;
    
    % handles of seed points (declaration of variable)
    lsSeed = zeros(maxfit,1);
    
    % handles of fitted curves (declaration of variable)
    if size(X,1) < 3
        lsCurve = zeros(maxfit,1);
    end
    
    % plot data set
    dataline(X, 'Parent', ax, 'Color', 'b', 'LineStyle', 'none', 'Marker', '.');
    
    % handles of neighborhood data sets (declaration of variable)
    lsNeighbors = zeros(maxfit,1);
    
    % scale axes
    datascale(X);
    
    % register callback functions
    set(fig, 'WindowButtonDownFcn', @neighborhood_figure_onmousedown);

    function neighborhood_figure_onmousedown(~, ~)
    % Fired when the user presses the mouse button.

        ix = find_closest(X, ax);
        switch get(fig, 'SelectionType')
        case 'normal'
            if numfit > 0
                % delete all previous plots
                for k = 1 : numfit
                    delete(lsNeighbors(k));
                    lsNeighbors(k) = 0;
                    if size(X,1) < 3
                        delete(lsCurve(k));
                        lsCurve(k) = 0;
                    end
                    delete(lsSeed(k));
                    lsSeed(k) = 0;
                end
            end
            numfit = 1;
        case 'extend'
            if numfit < maxfit
                numfit = numfit + 1;
            else
                return;  % no additional plots can be added
            end
        end
        
        % add new plot
        nix = neighborhood{ix};
        lsNeighbors(numfit) = dataline(X(:,nix), 'Parent', ax, 'Color', 'r', 'LineStyle', 'none', 'Marker', 's');
        if size(X,1) < 3
            lsCurve(numfit) = imconic(Theta(:,ix));
        end
        lsSeed(numfit) = dataline(X(:,ix), 'Parent', ax, 'Color', 'k', 'LineStyle', 'none', 'Marker', 's', 'MarkerFaceColor', 'k');
    end
end
