function pnew = seglink7(pold,width)
%
% seglink7 - determines 3 best segment neighbors both above and
%           below each segment [puts in properties 16-21]
% On input:
%     pold: segment properties
%     width: known width of band (or use avg)
% On output:
%     pnew: segment properties with links to neighbors added
%           [segment link with self number means nil]
% Call:
%     pnew = seglink7(pold,width)
%  16,17,18 -> 4,5,6  19,20,21 -> 7,8,9
[n,dummy] = size(pold); pnew = pold;
for s1 = 1:n                              % set link to self
  pnew(s1,4:9) = [s1,s1,s1,s1,s1,s1];   % segdist returns big num 
end;                                      % for self distance

CLEFT = 1; CRIGHT = 2; CROW = 1; CCOL = 2;
for s1 = 1:n
  s1row = pnew(s1,CROW); s1col = pnew(s1,CCOL);
  s1left = s1col-(width/2); s1right = s1col+(width/2);
  for s2 = 1:n
    if s1 ~= s2
      sup1 = pnew(s1,4); sup2 = pnew(s1,5); sup3 = pnew(s1,6);
      sdn1 = pnew(s1,7); sdn2 = pnew(s1,8); sdn3 = pnew(s1,9);
      dup1 = segdist(pnew(sup1,CROW),pnew(sup1,CCOL),s1row,s1col); % distance up
      dup2 = segdist(pnew(sup2,CROW),pnew(sup2,CCOL),s1row,s1col);
      dup3 = segdist(pnew(sup3,CROW),pnew(sup3,CCOL),s1row,s1col);
      ddn1 = segdist(pnew(sdn1,CROW),pnew(sdn1,CCOL),s1row,s1col); % distance dn
      ddn2 = segdist(pnew(sdn2,CROW),pnew(sdn2,CCOL),s1row,s1col);
      ddn3 = segdist(pnew(sdn3,CROW),pnew(sdn3,CCOL),s1row,s1col);
      s2row = pnew(s2,CROW); s2col = pnew(s2,CCOL);
      s2left = s2col-(width/2); s2right = s2col+(width/2);
      if (abs(s1left-s2left)<width/2) | (abs(s1right-s2right)<width/2) % if within column range
        d12 = segdist(s1row,s1col,s2row,s2col); % get seg distance
	if s1row<s2row   % if seg2 below seg1
	  segs = [sdn1,sdn2,sdn3,s2]; dist = [ddn1,ddn2,ddn3,d12];
	  [dists,disti] = sort(dist);
	  pnew(s1,7) = segs(disti(1));
	  pnew(s1,8) = segs(disti(2));
	  pnew(s1,9) = segs(disti(3));
	elseif s1row>s2row    % if seg2 above seg1
	  segs = [sup1,sup2,sup3,s2]; dist = [dup1,dup2,dup3,d12];
	  [dists,disti] = sort(dist);
	  pnew(s1,4) = segs(disti(3));
	  pnew(s1,5) = segs(disti(2));
	  pnew(s1,6) = segs(disti(1));
	end
      end
    end
  end
end
