function [ pn, dist ] = quadrilateral_point_near ( q, p )

%*****************************************************************************80
%
%% quadrilateral_point_near() computes the nearest point on a quadrilateral.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    18 January 2007
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real Q(2,4), the quadrilateral vertices.
%
%    real P(2), the point whose nearest quadrilateral point
%    is to be determined.
%
%  Output:
%
%    real PN(2), the nearest point to P.
%
%    real DIST, the distance from the point to the quadrilateral.
%
  dim_num = 2;
  nside = 4;
%
%  Find the distance to each of the line segments that make up the edges
%  of the quadrilateral.
%
  dist = Inf;
  pn(1:dim_num) = 0.0;

  for j = 1 : nside

    jp1 = i4_wrap ( j+1, 1, nside );

    [ pn2, dist2, tval ] = segment_point_near ( q(1:dim_num,j)', ...
      q(1:dim_num,jp1)', p );

    if ( dist2 < dist )
      dist = dist2;
      pn(1:dim_num) = pn2(1:dim_num);
    end

  end

  return
end
