% Simple forest fire model

function fire(n,p)

% n is size of square array (lattice)
% p is probability site is occupied (0 < p < 1)


AA=rand(n);  % matrix of uniformly distributed random numbers from (0,1)


% convert into 0,1 values

for i=1:n
    for j=1:n
      if AA(i,j)<p ; 
          AA(i,j)=0;  % black is tree 
      else AA(i,j)=1;
      end
    end
end

A=AA;   %AA is initial distribution, AA will be evolved lattice


% set initial fire along first column

for i=1:10:n
    A(i,1)=10;
end




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  nearest neighbor interaction

for m=1:20  %number of sweeps through lattice

for j=2:n-1
    for i=2:n-1
        if A(i,j)<0.5  % if there's a tree here 
            
        if A(i-1,j)>9 % if this tree is on fire (how long does it burn?)
            A(i,j)=10; % burned tree is white!
        end
        if A(i+1,j)>9 
            A(i,j)=10; 
        end
        if A(i,j-1)>9 
            A(i,j)=10; 
        end
        if A(i,j+1)>9 
            A(i,j)=10; 
        end
        if A(i-1,j-1)>9
            A(i,j)=10;
        end
        if A(i+1,j-1)>9
            A(i,j)=10;
        end
        if A(i+1,j-1)>9
            A(i,j)=10;
        end
        if A(i+1,j+1)>9
            A(i,j)=10;
        end
        end            
    end
end

end

% stretch contrast for better viewing

A=100*A;
AA=100*AA;
     
 
    assignin('base','A',A);
    assignin('base','AA',AA);

    imwrite(AA,'Afire','gif');
    imwrite(A,'fire','gif');

end