function output = Game_of_Life( input, duration , pause_length)
%GAME_OF_LIFE plays John Conway's Game of Life with the specified input.

[n,~]=size(input);
workinput=input;

for i=1:duration
    for j=1:n^2
        adjacent_inds=zeros(1,8);
        adjacent_inds(1)=mod(j-1,n.^2);
        adjacent_inds(2)=mod(j-1+n,n.^2);
        adjacent_inds(3)=mod(j+n,n.^2);
        adjacent_inds(4)=mod(j+n+1,n.^2);
        adjacent_inds(5)=mod(j+1,n.^2);
        adjacent_inds(6)=mod(j-n+1,n.^2);
        adjacent_inds(7)=mod(j-n,n.^2);    
        adjacent_inds(8)=mod(j-n-1,n.^2);
        adjacent_inds(adjacent_inds==0)=n.^2;
        neighbor_count=sum(input(adjacent_inds));
        if input(j)==1 && neighbor_count<2
            workinput(j)=0;
        elseif input(j)==1 && neighbor_count>3
            workinput(j)=0;
        elseif input(j)==0 && neighbor_count==3
            workinput(j)=1;
        end
    end
    input=workinput;
    figure(1);
    imagesc(input);
    title(num2str(i))
    waitbar(i/duration)
    pause(pause_length)
end

output=input;
end

