%This needs to pick the next cell to work on

function newindex = flow(x,y,xi,yi,z)
p=0;
diff = 0 ;
if ( xi <= 1 | xi == x | yi <=1 | yi == y )
    location = rain(x,y);
    newindex(1) = location(1);
    newindex(2) = location(2);
    newindex(3) = 0;
    return
else
           left = z(xi,yi) - z(xi-1,yi);
           right = z(xi,yi) - z(xi+1,yi);
           up = z(xi,yi) - z(xi,yi+1);
           down = z(xi,yi) - z(xi,yi-1);
         
           randcount = 0;
           
            ni = [ 0 0 ];
            %Finds out the most downhill cell
            if ( left < right )
               
                ni = [ xi+1, yi ];
                diff = right;
            end   
                
           if ( diff < up )
                
                ni = [ xi, yi+1 ];
                diff = up;
           end
                
          if ( diff < down )
                
                ni = [ xi, yi-1 ];
                diff = down;
                
          end
                
          if ( diff < left )
                
                ni = [xi+1, yi ];
                diff = left;
                
           end
            
            %May be useless
            %if (diff+30 < left | right| up| down )
            %    location = rain(x,y);
           %      newindex(1) = location(1);
           %      newindex(2) = location(2);
           %      newindex(3) = 0;
          %      return
          %  end
            
            
            rval = rand;

            if (diff > 1 )
                
                if (rval <= 0.25)
                     ni = [ xi-1, yi ];
                elseif (rval <= 0.5)
                     ni = [ xi+1, yi];
                elseif (rval <= 0.75)
                    ni = [ xi, yi+1 ];
                else
                     ni = [ xi, yi-1 ];
                end
                p= 1;
            end

                newindex(3) = p;
                newindex(1) = ni(1);
                newindex(2) = ni(2);
end