function distance_figure(X, Theta)
% Visualizes the pair-wise distance between points and shapes.
%
% Input arguments:
% X:
%    data set with dimensions [n,N]
% Theta:
%    parameter estimates
% D:
%    the matrix of distances [N,N] between points and shapes

% Copyright 2012 Levente Hunyadi

    fig = figure;
    ax = axes('Parent', fig);
    maxfit = 3;  % maximum number of fits
    numfit = 0;

    % handles of basis points (declaration of variable)
    lsBasis = zeros(maxfit,1);

    % handles of fitted curves (declaration of variable)
    lsCurve = zeros(maxfit,1);

    % plot data
    line(X(1,:), X(2,:), ...
        'Parent', ax, ...
        'Color', 'b', ...
        'LineStyle', 'none', ...
        'Marker', '.', ...
        'HitTest', 'off' ...  % not selectable my mouse click
    );
    
    % scale axes
    xlim([min(X(1,:)), max(X(1,:))]);
    ylim([min(X(2,:)), max(X(2,:))]);
    colors = {'k','r','g'};
    linestyles = {'-','--','-.'};
    markerstyles = {'^','s','p'};
    
    % register callback functions
    set(fig, 'WindowButtonDownFcn', @distance_figure_onmousedown);

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

        cp = get(ax, 'CurrentPoint');
        distsq = sum(bsxfun(@minus, X, [cp(1,1) ; cp(1,2)]).^2, 1);
        [~,ix] = min(distsq);  % point closest to selected
        
        switch get(fig, 'SelectionType')
        case 'normal'
            if numfit > 0
                % delete all previous plots
                for k = 1 : numfit
                    delete(lsCurve(k));
                    lsCurve(k) = 0;
                    delete(lsBasis(k));
                    lsBasis(k) = 0;
                end
            end
            numfit = 1;
        case 'extend'
            if numfit < maxfit
                numfit = numfit + 1;
            else
                return;  % no additional plots can be added
            end
        end
        
        lsCurve(numfit) = imconic(Theta(:,ix), [], ax, ...
            'Color', colors{numfit}, ...
            'LineStyle', linestyles{numfit}, ...
            'LineWidth', 2 ...
        );
        lsBasis(numfit) = line( ...
            'XData', X(1,ix), ...
            'YData', X(2,ix), ...
            'Parent', ax, ...
            'Color', colors{numfit}, ...
            'LineStyle', 'none', ...
            'Marker', markerstyles{numfit}, ...
            'MarkerFaceColor', colors{numfit} ...
        );
    end
end
