%This software implements the point matching algorithm described in the paper:
%"Rotation Invariant Nonrigid Point Set Matching in Cluttered Scenes", IEEE transaction on Image Processing, 2012

%Author: Wei Lian (Changzhi University, Changzhi, 046011, Shanxi Province, P.R. China, Email: lianwei3 at gmail.com)

%If you use this software for research purposes, you should cite the aforementioned paper in any resulting publications.


function [X]=choose_refer_and_recirc(X,openness)
%%choose reference point and reswitch point set X to make reference point the first point
%%X: Nx x dim
Nx=size(X,1);
switch openness
    case 'open'
        %%%resort X for open contour
        dif=X-X([2:Nx,1],:);
        edgelen=sqrt(sum(dif.^2,2));
        ind=find(edgelen==max(edgelen));
        ind=ind(1);
        X=X([ind+1:Nx,1:ind],:);%%sort to break at the longest edge
        dif=repmat(permute(X,[1,3,2]),[1,2,1])-repmat(permute(X([1,Nx],:),[3,1,2]),[Nx,1,1]);%%Nx x 2 x dim
        dist=sqrt(sum(dif.^2,3));%%Nx x 2 
        dist=sum(dist);
        dmax=max(dist);
        ind=find(dist==dmax);
        if ind(1)==2%%choose the last point as the head
            X=flipud(X);
        end        
    case 'close'
        %%find the point with total maximal distance from the rest in X
        dif=repmat(permute(X,[1,3,2]),[1,Nx,1])-repmat(permute(X,[3,1,2]),[Nx,1,1]);
        dist=sqrt(sum(dif.^2,3));
        dist=sum(dist);
        ind=find(dist==max(dist));
        ind=ind(1);
        X=X([ind:Nx,1:ind-1],:);%%resort to let ind as the head
end
