function [R,D1] = DLA(S,n)
% DLA.m
% 
% This code simulates DNA for a box of size 2S + 1 for n steps.
%
% Usage: [R, D1] = DLA(S, n)
% 'S' box half-width (extra pixel added for symmetry)
% 'n' number of steps

R=zeros(n,1);
D1=zeros(2*S+1);
D2=D1;
D1(S+1,S+1)=1;
figure(1);
image(60*D1);
for m=1:n
    D2=zeros(2*S+1);
    [l1 l2]=pol2cart(2*pi*rand(1),S-1);
    loc=floor([l1 l2]);
    loc=loc+[S+1 S+1];
    D2((loc(1)-1):(loc(1)+1),(loc(2)-1):(loc(2)+1))=ones(3);
    % figure(2)
    % % axis square
    % image(60*D2)
    % axis square
    % drawnow
    while max(max(D1+D2))==1
        step=(-1)^round(rand(1));
        ind=round(1+rand(1));
        z=zeros(1,2);
        z(ind)=step;
        D2=circshift(D2,z);
    %   image(60*(D2+D1))
    %   drawnow
    end
    D1(mean(find(D2==1)))=1;
    figure(1);
    image(60*D1);
    drawnow
    m
    [row, col]=find(D1==1);
    row=row-(S+1);
    col=col-(S+1);
    R(m)=sqrt(max(row.^2+col.^2));
end

figure(1);
image(60*D1);
drawnow

end