function [ d, v, w ] = diophantine_2d_basis ( a, b )

%*****************************************************************************80
%
%% diophantine_2d_basis: solution space basis of a Diophantine equation in 2 variables.
%
%  Discussion:
%
%     Given the Diophantine equation 
%
%       a1 x1 + a2 x2 = b
%
%     we are seeking all possible integer solutions x.
%
%     This function analyzes the coefficient vector a, and returns
%     a value d, an vector v, and a vector w so that:
%     * The value b must be divisible by d;
%     * v is a solution;
%     * General solutions have the form x = v + w * c
%       where c is an arbitrary integer coefficient.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    08 April 2020
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer a(2): the coefficients of the Diophantine equation.
%
%    integer b: the right hand side.
%
%  Output:
%
%    integer d: a value that must be a factor of the right hand side.
%
%    integer v(2): a particular solution.
%
%    integer w(2): the general solution basis vector.
%
  if ( any ( a == 0 ) )
    error ( 'diophantine_2d_basis: a has a zero entry.' );
  end
%
%  Dimension the matrix.
%
  n = length ( a );
  if ( n ~= 2 )
    error ( 'diophantine_2d_basis: dimension of a must be 2.' );
  end

  np1 = n + 1;
%
%  Form the matrix: 
%
  A(1:n,1) = a(1:n);
  A(1:n,2:np1) = eye(n,n);
%
%  Perform repeated row reduction.
%
  while ( 1 < nnz ( A(1:n,1) ) )
%
%  Locate row containing nonzero entry of smallest magnitude.
%
    t = Inf;
    p = 0;
    for i = 1 : n
      s = abs ( A(i,1) );
      if ( s ~= 0 )
        if ( s < t )
          p = i;
        end
      end
    end
%
%  Swap row 1 and row p.
%
    T = A(1,1:np1);
    A(1,1:np1) = A(p,1:np1);
    A(p,1:np1) = T;
%
%  fix(r) rounds towards zero.
%
    for i = 2 : n
      s = fix ( A(i,1) / A(1,1) );
      A(i,1:np1) = A(i,1:np1) - s * A(1,1:np1);
    end

  end

  d = A(1,1);
  f = b / d;
  if ( f * d ~= b )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'diophantine_2d_basis - Warning!\n' );
    fprintf ( 1, '  b = %d is not a multiple of d = %d\n', b, d );
    fprintf ( 1, '  There are no integer solutions to this equation.\n' );
  end
  v = (A(1,2:np1))' * f;
  w = (A(2:n,2:np1))';

  return
end

