function [ success, l ] = find_distances ( l_length, l, x_length, x, y )

%*****************************************************************************80
%
%% find_distances() determines if the "free" distances include every |X(I)-Y|.
%
%  Discussion:
%
%    This routine is given a candidate point Y, a set of placed points
%    X(1:X_LENGTH), and a list of unused or "free" distances in
%    L(1:L_LENGTH).  The routine seeks to find in L a copy of the
%    distance from Y to each X.
%
%    If so, then the L array is reordered so that entries
%    L(L_LENGTH-X_LENGTH+1:L_LENGTH) contain theses distances.
%
%    In other words, Y can be added into X, and L_LENGTH reduced to
%    L_LENGTH-X_LENGTH.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    10 January 2018
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Pavel Pevzner,
%    Computational Molecular Biology,
%    MIT Press, 2000,
%    ISBN: 0-262-16197-4,
%    LC: QH506.P47.
%
%  Input:
%
%    integer L_LENGTH, the length of the array.
%
%    integer L(L_LENGTH), the array. 
%
%    integer X_LENGTH, the number of entries in X.
%
%    integer X(X_LENGTH), the number of points
%    already accepted.
%
%    integer Y, a new point that we are considering.
%
%  Output:
%
%    logical SUCCESS, is TRUE if the entries of L included
%    the values of the distance of Y to each entry of X.
%
%    integer L(L_LENGTH), if SUCCESS is TRUE,
%    the entries L(L_LENGTH-X_LENGTH+1:L_LENGTH) contain the distances
%    of X(1:X_LENGTH) to Y.
%
  l2_length = l_length;

  for i = 1 : x_length

    d = abs ( x(i) - y );

    success = false;;

    for j = 1 : l2_length

      if ( l(j) == d )
        l(j) = l(l2_length);
        l(l2_length) = d;
        l2_length = l2_length - 1;
        success = true;
        break
      end

    end

    if ( ~ success )
      return
    end

  end

  success = true;

  return
end
