function i = hammersley_inverse ( r, m, n )

%*****************************************************************************80
%
%% hammersley_inverse() inverts an element of the Hammersley sequence.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    18 August 2016
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real R(M), the I-th element of the Hammersley sequence.
%    0 <= R < 1.0
%
%    integer M, the spatial dimension.
%
%    integer N, the "base" for the first component.
%    1 <= N.
%
%  Output:
%
%    integer I, the index of the element of the sequence.
%
  if ( any ( r < 0.0 ) | any ( 1.0 < r ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'HAMMERSLEY_INVERSE - Fatal error!\n' );
    fprintf ( 1, '  0 <= R <= 1.0 is required.\n' );
    error ( 'HAMMERSLEY_INVERSE - Fatal error!' );
  end

  if ( m < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'HAMMERSLEY_INVERSE - Fatal error!\n' );
    fprintf ( 1, '  1 <= M is required.\n' );
    error ( 'HAMMERSLEY_INVERSE - Fatal error!' );
  end

  if ( n < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'HAMMERSLEY_INVERSE - Fatal error!\n' );
    fprintf ( 1, '  1 <= N is required.\n' );
    error ( 'HAMMERSLEY_INVERSE - Fatal error!' );
  end
%
%  Invert using the second component, if possible.
%
  if ( 2 <= m )
    i = 0;
    t = r(2);
    p = 1;
    while ( t ~= 0.0 )
      t = t * 2.0;
      d = t - mod ( t, 1.0 );
      i = i + d * p;
      p = p * 2;
      t = mod ( t, 1.0 );
    end
%
%  Invert using component 1.
% 
  else

    i = round ( n * r(1) );

  end

  return
end

