function d = triangle_distance ( t, p )

%*****************************************************************************80
%
%% triangle_distance() determines the distance from P to triangle T).
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 July 2023
%
%  Author:
%
%    John Burkardt
%
  a = t(1,1:2);
  b = t(2,1:2);
  c = t(3,1:2);

  dab = line_parameter_t ( a, b, p );
  dbc = line_parameter_t ( b, c, p );
  dca = line_parameter_t ( c, a, p );
%
%  Three negatives, inside triangle, distance is zero.
%
  if ( dab <= 0.0 && dbc <= 0.0 && dca <= 0.0 )
    d = 0.0;
    return
  end
%
%  Two negative, one positive, distance is the positive one.
%
  if ( 0.0 <= dab && dbc <= 0.0 && dca <= 0.0 )
    d = dab;
    return
  elseif ( dab <= 0.0 && 0.0 <= dbc && dca <= 0.0 )
    d = dbc;
    return
  elseif ( dab <= 0.0 && dbc <= 0.0 && 0.0 <= dca )
    d = dca;
    return
  end
%
%  One negative, two positives.  Determine closest vertex.
%
  if ( dab <= 0.0 )
    d = norm ( c - p );
  elseif ( dbc <= 0.0 )
    d = norm ( a - p );
  elseif ( dca <= 0.0 )
    d = norm ( b - p );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, '  dAB = %f\n', dab );
    fprintf ( 1, '  dBC = %f\n', dbc );
    fprintf ( 1, '  dCA = %f\n', dca );
    d = Inf;
  end

  return
end
