% Copyright (c) Wei Lian (2010,2011), Department of computer science, Changzhi University, Changzhi, Shanxi province, China
function [X]=choose_refer_and_recirc(X,openness)

Nx=size(X,1);
switch openness
    case 'open'
        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],:);
        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));
        dist=sum(dist);
        dmax=max(dist);
        ind=find(dist==dmax);
        if ind(1)==2
            X=flipud(X);
        end        
    case 'close'
        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],:);
end