function segments=find_segments_to_smooth(pts,pri,edges)
% consider each primary point in turn and create a list of points to which
% it is linked up to and including the next primary point
segments={};
allsecondarysegs=[];
k=0;
temp_pri=pri;
temp_edges=edges;
while length(temp_pri)>0
    p=temp_pri(1);  % take a primary point
    temp_pri(1)=[]; % remove from list
    if length(temp_pri)>0 % to form an arc there must be a primary ending
        [primary_connections]=get_connections(edges,p);
        not_wanted=intersect(primary_connections,allsecondarysegs); % because already seen
        for jj=1:length(not_wanted)
            ind=find(primary_connections==not_wanted(jj));
            primary_connections(ind)=[];
        end
        for j=1:length(primary_connections) % chase down each in turn
            primary_connection=primary_connections(j);
            seg=p;
            connection=primary_connection;
            while isempty(find(pri==connection))
                seg=[seg,connection];
                allsecondarysegs=[allsecondarysegs,connection];
                index=find(edges==connection);
                if ~isempty(index)
                    [connections]=get_connections(edges,connection);
                    if length(connections)~=2
                        uiwait(warndlg(sprintf('Secondary points must be linked through edges:\n Point %d should be connected to 2 others',connection)));
                        return; %error(sprintf('Edges not properly linked to make secondary points:\n Point %d should be connected to 2 others',connection));
                    end
                    not_wanted=intersect(connections,seg); % because already in seg
                    for jj=1:length(not_wanted)  % could use setdiff() here
                        ind=find(connections==not_wanted(jj));
                        connections(ind)=[];
                    end
                    if length(connections)>1 %there should only be one entry
                        error('secondary landmark has more than two edges');
                    end
                    if ~isempty(connections)
                        connection=connections(1);
                    else
                        %error('secondary landmark must be connected two landmarks');
                    end
                end
            end
            if length(seg)>1
                seg=[seg,connection]; % final landmark must be a primary
                k=k+1;
                segments{k}=seg;
            end
        end
    end
end

function [connections,edges]=get_connections(edges,p)
indleft=find(edges(:,1)==p);
indleft=indleft(:)';
if ~isempty(indleft)
    connections=edges(indleft,2);
    %edges(indleft,:)=[];
else
    connections=[];
end
indright=find(edges(:,2)==p);
indright=indright(:)';
temp=edges(indright,1);
if ~isempty(indright)
    connections=[connections(:)',temp(:)'];
    %edges(indleft,:)=[];
end
