format long
set(0,'RecursionLimit',10000);

binnum = 25; %Number of bins
areabins = (1/binnum:1/binnum:1).';
allperccounts = zeros(binnum,1);
alltotalcounts = zeros(binnum,1);

directoryName = './Data/MeltPondMats/';
files = dir(directoryName);
fileIndex = find(~[files.isdir]);
fileIndex = fileIndex(2:end);

for i = 1:length(fileIndex)
        
%Load the Image
fileName = files(fileIndex(i)).name;
load(strcat(directoryName,fileName))
z = +A;

%Analyze the level sets 
Out = CriticalArea(z); 
    %Out = [AreaFraction,PathExist,NumObjects,pondareas];

%Create a cell structure for binning the results
areadata = horzcat(areabins, zeros(binnum,2));

%Extract Area Fraction data and the presence of percolation
AreaFraction = cell2mat(Out(1,1)); 
PathExist = cell2mat(Out(1,2)); 

%Determine which bin to place the data
bin = ceil(AreaFraction*binnum);
if bin == 0
    bin = 1;
end
%Add data from level set to resultant bin
areadata(bin,2) = areadata(bin,2) + PathExist;
areadata(bin,3) = areadata(bin,3) + 1;

perccounts = areadata(:,2);
totalcounts = areadata(:,3);

allperccounts = allperccounts + perccounts;
alltotalcounts = alltotalcounts + totalcounts;
end             

allavecounts = allperccounts./alltotalcounts;
        
%filename = strcat('Brady_0.2_0.2.mat');
%save(filename,'areabins','allavecounts')
