function lout = lanes3(lin,lt)
% lout = lanes3(lin,lt)
%
% On input:
%          lin: input lanes
%          lt:  merge threshold
[m n] = size(lin);
lanes = lin;
mindex = 0;
for l1 = 1:m-1   % identify lanes close enough (in rho) to merge
  rho1 = lanes(l1,6);
  for l2 = l1+1:m
    rho2 = lanes(l2,6);
    if abs(rho1-rho2)<lt
      m1 = lanes(l1,8); m2 = lanes(l2,8);
      if (m1==0) & (m2==0)  % put 2 ungrouped lanes in new group
        mindex = mindex+1;
        lanes(l1,8) = mindex;
        lanes(l2,8) = mindex;
      elseif (m1~=0) & (m2==0)  % put l2 in l1'2 group
        lanes(l2,8) = lanes(l1,8);
      elseif (m1==0) & (m2~=0)  % form new l1 group if l2 closer
        dif = abs(rho1-rho2); closer = 1;
        for l3 = 1:l1-1
          if (lanes(l3,8)==m2) & (abs(lanes(l3,6)-rho2)<dif)
            closer = 0;
          end
        end
        if closer>0
          mindex = mindex+1;
          lanes(l1,8) = mindex; lanes(l2,8) = mindex;
        end
      else  % both already in group; put l2 in l1's group if closer
	   if m1~=m2
        dif = abs(rho1-rho2);
        closer = 1;
        for l3 = 1:l1-1
          if (lanes(l3,8)==m2) & abs(lanes(l3,6)-rho2)<=dif
            closer = 0;
          end
        end
        if closer>0
          lanes(l2,8) = lanes(l1,8);
        end
	   end
      end
    end
  end
end
mcount = zeros(m,1);   % count lanes in merged sets
for l1 = 1:m
  lc = lanes(l1,8);
  if lc>0
    mcount(lc) = mcount(lc)+1;
  end
end
for l1 = 1:m           % delete singleton merged sets
  lc = lanes(l1,8);
  if lc>0
    if mcount(lc) == 1
      lanes(l1,8) = 0;
    end
  end
end
nindex = 0; nummer = max(lanes(:,8)); used = zeros(nummer,1);
for l1 = 1:m
  m1 = lanes(l1,8);
  if m1 == 0
    nindex = nindex+1;
    for j1 = 1:8
      lout(nindex,j1) = lanes(l1,j1);
    end
  else
    if used(m1)==0
      nindex = nindex+1;
      rmin = lanes(l1,1); rmax = lanes(l1,3); used(m1) = 1;
      cmin = lanes(l1,2); cmax = lanes(l1,4);
      for l2 = l1+1:m
        if lanes(l2,8)==m1
          if lanes(l2,1)<rmin
            rmin = lanes(l2,1);
            cmin = lanes(l2,2);
          end
          if lanes(l2,3)>rmax
            rmax = lanes(l2,3);
            cmax = lanes(l2,4);
          end
        end
      end
      for j1 = 1:8
        lout(nindex,j1) = lanes(l1,j1);
      end
      lout(nindex,1) = rmin; lout(nindex,3) = rmax;
      lout(nindex,2) = cmin; lout(nindex,4) = cmax;
    end
  end
end
