function [PathExist] = CoordTraverseStack(x,y,r,c)
%As an alternative to image thresholding algorithms, we design an 
%"edge follower" which will follow the boundaries between 0s (Sea Ice) and
%1s (Melt Ponds), with 2s representing unchecked melt pond pixels adjacent
%to -1s, the path(s) taken
%
%INPUTS
%  Lat = Level set with 1s and 0s representing melt ponds and sea ice
%    x = The x-position which the traverse function currently is located at
%    y = The y-position which the traverse function currently is located at
%    r = Number of rows in Lat (1000 for continuum model data)
%    c = Number of columns in Lat (1000 for continuum model data)
%
%OUTPUTS
%  PathExist = 0 (no path/percolation) or 1 (path/percolation exists)
%
%By: Anthony Cheng (Mar 2015)
%===================================================================

global Lat
PathExist = 0;

% Implement a stack for more efficiency (compared to recursion)
% Stack (LIFO) rather than Queue because it is generally unnecessary to
% check every single potential neighbor - we want to get to the opposite side 
% as quickly as possible
stack = java.util.Stack;
node = [x,y,Lat(y,x)];
stack.push(node);

TF = stack.empty();

while TF == 0;
    %Pop returns the first element (node) on the top of the stack
    Popped = stack.pop();
    
    %If the second element of the node is bigger than r, we have reached
    %the other side, so we break.
    if Popped(2,1) >= r
        PathExist = 1;
        break
    else
    end
    
    %If we start on a sea ice vertex (value 0) or melt pond vertex not on 
    %the boundary (value 1), we disregard it.
    if Popped(3,1) <= 1
        TF = stack.empty();
        continue
    else
    end
    
    if Popped(3,1) == 2
        %We mark all visited vertices with -1 to show they have been visited.
        Lat(Popped(2,1),Popped(1,1)) = -1;
        
        %Find neighbors of our current vertex that are marked as Melt Ponds
        %on the boundary (2), and add them to the set of neighbors Neigh to 
        %reiterate process
        Neigh = [];
        Neighout = get8NeighCheck2(Popped(1,1),Popped(2,1),Lat,r,c);
        Neigh = cat(1,Neigh,Neighout);
        
        %If there exist any, add to stack.
        NeighSize = size(Neigh);
        NeighNum = NeighSize(1,1);
        for n = 1:NeighNum
            %Value assigned to Neighbor is L(y,x), Neigh(n,2);
            %Neigh(n,1) = the nth y;x
            neighVal = Lat(Neigh(n,2),Neigh(n,1));
            node = [Neigh(n,1),Neigh(n,2),neighVal];
            stack.push(node);
        end
        
        TF = stack.empty();
    else
    end
end

end