function pi_spigot ( n )

%*****************************************************************************80
%
%% pi_spigot() implements the "pi spigot" algorithm for digits of pi.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    23 February 2019
%
%  Author:
%
%    Original Pascal program by Simeon Simeonov.
%    Matlab version by John Burkardt
%
%  Reference:
%
%    Stanley Rabinowitz, Stan Wagon,
%    A spigot algorithm for the digits of pi,
%    American Mathematical Monthly,
%    Volume 102, Number 3, pages 195-203, March 1995.
%
%  Parameeters:
%
%    Input, integer N, the number of digits to compute.
%
  len = floor ( ( 10 * n ) / 3 );

  a = 2 * ones ( len, 1 );
  nines = 0;
  predigit = 0;

  for j = 1 : n

    q = 0;
    for i = len : -1 : 1
      x = 10 * a(i) + q * i;
      a(i) = mod ( x, 2 * i - 1 );
      q = floor ( x / ( 2 * i - 1 ) );
    end

    a(1) = mod ( q, 10 );
    q = floor ( q / 10 );

    if ( q == 9 )
      nines = nines + 1;
    elseif ( q == 10 )
      fprintf ( 1, '%d', predigit + 1 );
      for k = 1 : nines
        fprintf ( 1, '0' );
        predigit = 0;
        nines = 0;
      end
    else
      if ( 1 < j )
        fprintf ( 1, '%d', predigit );
      end
      if ( j == 2 )
        fprintf ( 1, '.' );
      end
      predigit = q;
      if ( nines ~= 0 )
        for k = 1 : nines
          fprintf ( 1, '9' );
        end
        nines = 0;
      end
    end

  end

  fprintf ( 1, '%d\n', predigit );

  return
end

