function fern_chaos ( n )

%*****************************************************************************80
%
%% fern_chaos() displays the Barnsley fractal fern.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 May 2011
%
%  Author:
%
%    Original code by Cleve Moler.
%    This version by John Burkardt.
%
%  Reference:
%
%    Michael Barnsley,
%    Fractals Everywhere,
%    Academic Press, 1988,
%    ISBN: 0120790696,
%    LC: QA614.86.B37.
%
%    Cleve Moler,
%    Experiments with MATLAB,
%    ebook: https://www.mathworks.com/moler/exm/index.html
%
%  Input:
%
%    integer N, the number of points to display.
%    A value of 10,000 or so is enough to see the fern.
%    For values of 500 or less, larger dots are displayed to suggest
%    how the plot is drawn.
%
  if ( nargin < 1 )
    n = 10000;
  end

  prob = [ 0.85, 0.92, 0.99, 1.00 ];
%
%  Compute the points.
%
  p = zeros ( n, 2 );

  p(1,1:2) = rand ( 1, 2 );

  for i = 2 : n

    r = rand ( 1, 1 );

    if ( r < prob(1) )
      p(i,1) =   0.85 * p(i-1,1) + 0.04 * p(i-1,2) + 0.0;
      p(i,2) = - 0.04 * p(i-1,1) + 0.85 * p(i-1,2) + 1.6;
    elseif ( r < prob(2) )
      p(i,1) =   0.20 * p(i-1,1) - 0.26 * p(i-1,2) + 0.0;
      p(i,2) =   0.23 * p(i-1,1) + 0.22 * p(i-1,2) + 1.6;
    elseif ( r < prob(3) )
      p(i,1) = - 0.15 * p(i-1,1) + 0.28 * p(i-1,2) + 0.0;
      p(i,2) =   0.26 * p(i-1,1) + 0.24 * p(i-1,2) + 0.44;
    else
      p(i,1) =   0.00 * p(i-1,1) + 0.00 * p(i-1,2) + 0.0;
      p(i,2) =   0.00 * p(i-1,1) + 0.16 * p(i-1,2) + 0.0;
    end

  end
%
%  Plot the points as small green dots.
%
  if ( n <= 500 )
    dot_size = 5;
  else
    dot_size = 1;
  end

  clf ( );
  plot ( p(:,1), p(:,2), 'g.', 'MarkerSize', dot_size );
  axis ( 'equal' );
  axis ( [ -3.0, +3.0, -1.0, 11.0 ] );
  label = sprintf ( 'Fractal Fern, N = %d', n );
  title ( label );
  filename = 'fern_chaos.png';
  print ( '-dpng', filename );
  fprintf ( 1, '  Graphics saved as "%s"\n', filename );

  return
end

