function [output] = link(input)

IMAX = max(max(input));
[m n] = size(input);
k=1;
for i= 2:m-1
  for j= 2:n-1

     if input(i,j) ~= 0
       if input(i,j-1) ~= 0 & input(i,j) ~= input(i,j-1)
          table(k,:) = [ min([ input(i,j) input(i,j-1) ]) max([ input(i,j) input(i,j-1) ])];
          k=k+1;
       end
       if input(i,j+1) ~= 0 & input(i,j) ~= input(i,j+1)
          table(k,:) = [ min([ input(i,j) input(i,j+1) ]) max([ input(i,j) input(i,j+1) ])];
          k=k+1;
       end
       if input(i-1,j-1) ~= 0 & input(i,j) ~= input(i-1,j-1)
          table(k,:) = [ min([ input(i,j) input(i-1,j-1) ]) max([ input(i,j) input(i-1,j-1) ])];
          k=k+1;
       end
       if input(i-1,j) ~= 0 & input(i,j) ~= input(i-1,j)
          table(k,:) = [ min([input(i,j) input(i-1,j) ]) max([input(i,j) input(i-1,j) ])];
          k=k+1;
       end
       if input(i-1,j+1) ~= 0 & input(i,j) ~= input(i-1,j+1)
          table(k,:) = [ min([input(i,j) input(i-1,j+1) ]) max([input(i,j) input(i-1,j+1) ])];
          k=k+1;
       end
       if input(i+1,j-1) ~= 0 & input(i,j) ~= input(i+1,j-1)
          table(k,:) = [ min([input(i,j) input(i+1,j-1) ]) max([input(i,j) input(i+1,j-1) ])];
          k=k+1;
       end
       if input(i+1,j) ~= 0 & input(i,j) ~= input(i+1,j)
          table(k,:) = [ min([input(i,j) input(i+1,j) ]) max([input(i,j) input(i+1,j) ])];
          k=k+1;
       end
       if input(i+1,j+1) ~= 0 & input(i,j) ~= input(i+1,j+1)
          table(k,:) = [ min([input(i,j) input(i+1,j+1) ]) max([input(i,j) input(i+1,j+1) ])];
          k=k+1;
       end
     end
   end
end

[m n] = size(table);

if m ~= 0
 [table2(:,1) index] = sort(table(:,1));
 table2(:,2) = table(index,2);
 table = table2;
end

table(m+1,:) = [0 0];

output1 = zeros(IMAX,10);
bsize = zeros(1,IMAX);

i=1;
while i<=m
   while table(i,1) == table(i+1,1)
      if table(i,2) ~= table(i+1,2)
         bsize(table(i,1)) = bsize(table(i,1)) + 1;
         output1(table(i,1),bsize(table(i,1))) = table(i,2);
      end
      i=i+1;
   end
   
   bsize(table(i,1)) = bsize(table(i,1)) + 2;
   output1(table(i,1),bsize(table(i,1))-1) = table(i,1);
   output1(table(i,1),bsize(table(i,1))) =  table(i,2);

   for j=1:bsize(table(i,1))
     output1( table(i,2) , bsize(table(i,2)) + j ) = output1( table(i,1), j );
     output1( table(i,1),j) = 0;
   end
   bsize(table(i,2)) = bsize(table(i,2))+bsize(table(i,1));   

   i=i+1;
end

[a b] = size(output1);
output2 = zeros(1,b);
j=1;
for i=1:a
   if max(output1(i,:)) ~= 0
      output2(j,:) = output1(i,:);
      j=j+1;
   end
end
output2 = sort(output2,2);

[c d]=size(output2);
output = 1:IMAX;
for i=1:c
     if max(max(output2)) == 0
        break;
     end
     j=1;
     while output2(i,j) == 0
        j = j+1;
	if j == d
	   break;
        end
     end
     
     minimum = output2(i,j);
     
     while j<=d 
       output(output2(i,j)) = minimum; 
       j = j+1;
     end
end




