function [D] = regionGrowing(I, x, y, t,imgCond)
%regionGrowing   Perform region growing
%
%	Usage: [D] = regionGrowing(I, x, y, t)
%
%		I = input image (must be the class of double)
%		x = row of seed location
%       y = column of seed location
%           (Note: This notations conflict with conventional notations.
%                  I just don't want to modify this code too much by
%                  x -> row and y -> col.) 
%       t = ??? (It could be non-integer value, such as 6.5)
%
%       D = binary output (0 and 1)
%
% Author:	Unknown
%
% Created:  November 22, 2002
% Modified: November 26, 2002


 %figure(1)
 %imshow(uint8(I));
 %hold on;plot(y,x,'+r');hold off;
 %pause;
 I = double(I);
 
 % Region Growing
 [m n] = size(I);
 %D = zeros(m, n); 
 D = logical(zeros(m, n,'uint8')); 

 
 %D(x-1:x+1, y-1:y+1) = 1;
 %figure 
 %imshow( D );
 %pause
 %D(x-1:x+1, y-1:y+1) = 0;
  
 position = [x y];
 rI = I(x,y);
 
 Dx = [ 0 -1 1  0];
 Dy = [ 1  0 0 -1];
 J = 0;
 Values = [];
 D(x, y) = 1;
 while ( not( isempty( position ) ) )
          
   [d s] = size(position);
   [p] = position(1:2);
  
   if (s == 2)
      position = [];
   else
      position = position(3:s);
   end
    
    x = p(1);
    y = p(2);
    
    %Values = [ Values; I(x,y) ];
    
    %
    % calculate mean
    %
    %Mr = mean(Values);
    
    
    %J = J + 1;
    %if ( J > 500 )
    %    imshow(D);
    %    drawnow;
        %Mr
    %    J = 0;
    %end
      
    for i=1:4,
        
         if ( (Dx(i)+x < 1) | (y +Dy(i)< 1) | (Dx(i)+x > m) | ( y +Dy(i)> n))
               continue;
        end
        
         % Centroid Method
         %if ( (abs(I(x+Dx(i), y+Dy(i))- Mr ) < t) & (D(x+Dx(i),y+Dy(i)) ~= 1) &
         %    (imgCond(x+Dx(i),y+Dy(i)) ~= 1)) 
        
         % Region 
         %if (  (abs(I(x+Dx(i), y+Dy(i))-I(x,y) ) < t) & (D(x+Dx(i),y+Dy(i)) ~= 1)) 
        
         %Seed Value
         if ( (abs(I(x+Dx(i), y+Dy(i))- rI) < t) & (D(x+Dx(i),y+Dy(i)) ~= 1) &...
                 (imgCond(x+Dx(i),y+Dy(i)) == 1) )
                 
                D( x+Dx(i), y+Dy(i) ) = 1;
                position = [position x+Dx(i) y+Dy(i)];
         end
    end
    
               
   end % while
       

return 
          