function Out = CriticalArea(melt)
%Determine if percolation occurs at each sampled level set, and the
%Area Fraction at each level set
%
%INPUTS
%  melt = r x c x z, matrix of z level sets, size r rows by c columns
%         r = 1000, c = 1000 for Continuum Model data
%         z = h from CutLevelSets.m
%
%OUTPUTS
%   Out = A z x k array which details the Area Fraction, the binary 
%         variable PathExist which indicates the presence of percolation
%         for each level set taken in melt, the number of objects (melt 
%         ponds) detected, and the size of each of those melt ponds. 
%
%By: Anthony Cheng (Mar 2015)
%===================================================================

[r, c, z] = size(melt);

Out = [];

%-------------------------------------------------------------------
%For each level set k for k = 1:z, calculate the Area Fraction
%("CriticalArea") and determine the presence of percolation ("PathExist")
%-------------------------------------------------------------------
for k = 1:z
    tic;
    draw = squeeze(melt(:,:,k));
    
    %Calculate the Area Fraction by counting number of non-empty "pixels" 
    AreaFraction = nnz(draw)/(r*c); 
    
    CC = bwconncomp(draw);
    NumObjects = CC.NumObjects;
    PixelIdxList = CC.PixelIdxList;
    
    boundregions = bwboundaries(draw);
    for boundaryiter = 1:length(boundregions)
        boundaries = boundregions(boundaryiter,1);
        boundaries = cell2mat(boundaries);
        
        for changeboundvalueiter = 1:(length(boundaries)-1)
            boundindex = boundaries(changeboundvalueiter,:);
            x = boundindex(1,1);
            y = boundindex(1,2);
            draw(x,y) = 2;
        end
    end
    
    PathExist = FindCoordPath(draw,r,c);
    ccszlist = zeros(1,NumObjects);
    for objiter = 1:NumObjects
        ccszlist(1,objiter) = length(cell2mat(PixelIdxList(objiter)));
    end
    pondareas = cell(1);
    pondareas{1,1} = ccszlist;
    
    Summary = [AreaFraction,PathExist,NumObjects,pondareas];
    Out = cat(1,Out,Summary);
    toc
end

end
