% MATLAB code for drawing DLA by Chris Bishop
% Calls auxilary file plotcirc.m

% This is a slow and verbose version that draws the 
% random walk used to choose the next attachment point 
% as a sequence of blue circles whose radius is the distance
% from the current step to the current aggregrate.
% When the walk moves too far from the origin, a new point 
% is chosen on a smaller circle using the Poisson kernel 
% with respect to the point where the walk hit the larger
% circle. 

% the input n is the number of particles to attach before stopping

function   out=dla_movie(n)
tic
   clear centers;
   clear lograd;
   tic;
   centers=[0];
   counter=1;
   maxradius=0;
   attempts=1;
   %centers=zeros(1,n);
   circle=exp(2*pi*i*[0:.01:1]);
   figure; hold on; axis equal; axis off;
   a=15;
  % plot([-a a a -a],[-a -a a a ],'w');
  plot(a*circle,'w');
   for k=1:length(centers)
       plot(centers(k)+circle,'k')
   end % for k 
  drawnow;
  while counter < n
      maxradius=max(abs(centers));
      a=max(a,3*maxradius);
      plot((maxradius+2)*circle,'r');
      z=(maxradius+2)* exp(2 * pi * i * random('unif',0,1));
      plot(z+circle,'b');
      drawnow;
      step=min(abs(z-centers))-2;
      while((step>.05))
         step=min(abs(z-centers))-2;
         oldz=z;
         if abs(oldz)> a/2
             z=exp(2*pi*i*rand);
             r=maxradius;
             z= (-r*z-1)/(-z-r);
             z= (maxradius+2)*z*conj(oldz)/abs(oldz);
             plot(abs(oldz)*circle,'r');
         else
           z=oldz+ step * exp( 2 * pi * i * random('unif',0,1));
         end % if
         plot([z,oldz],'b');
         plot(z+circle,'b');
         drawnow;
         drawnow;
         pause(.1);
      end
      if (step<.2)
          attempts=attempts+1;
              counter=counter+1;
              centers(counter)=z;
      end % if
      hold off;   
      % plot([-a a a -a],[-a -a a a ],'w');
         plot(a*circle,'w');
       hold on; axis equal; axis off;
     for k=1:length(centers)
          plot(centers(k)+circle,'k','LineWidth',2)
      end % for k 
     plot(centers(end)+circle,'r','LineWidth',2)
      drawnow;
      pause(1);
      %s=input('continue?');
     % if s==0
     %     break
     % end 
   end % while Counter < n
   toc
   
