 /*-----------------------------------------------------------------
 * Determine if polygon A overlaps polygon B by determining if
 * their bounding boxes overlap.
 *
 * XXX ought to do a more correct check?
 *-----------------------------------------------------------------*/
Datum
poly_overlap(PG_FUNCTION_ARGS)
{
	POLYGON    *polya = PG_GETARG_POLYGON_P(0);
	POLYGON    *polyb = PG_GETARG_POLYGON_P(1);
	LSEG				polyaedge, polybedge;
	bool		result;
	int i, j;

	result = box_ov(&polya->boundbox, &polyb->boundbox);

	/*
	 * Do more precise checks.  Check if at least one vertex in polyb is in 
	 * polya or vice versa
	 */

	if(result)
	{
		result = false;

		for (i = 0; i < polya->npts; i++)
		{
			if (point_inside(&(polya->p[i]), polyb->npts, 
											&(polyb->p[0])) > 0)
			{
				result = true;
				break;
			}
		}

		if(result == false)
		{
			for (i = 0; i < polyb->npts; i++)
			{
				if (point_inside(&(polyb->p[i]), polya->npts, 
												&(polya->p[0])) > 0)
				{
					result = true;
					break;
				}
			}
		}
		
		/*
		 * If the vertex tests failed, check that at least one of the edges of the 
		 * polygons intersect each other.
		 */

		if(result == false)
		{
			for(i = 0; i < polya->npts; i++)
			{
				if(i == polya->npts - 1)
				{
					statlseg_construct(&polyaedge, &(polya->p[0]),
												&(polya->p[i]));
				}
				else
				{
					statlseg_construct(&polyaedge, &(polya->p[i + 1]),
												&(polya->p[i]));
				}

				for(j = 0; j < polyb->npts; j++)
				{
					if(j == polyb->npts - 1)
					{
						statlseg_construct(&polybedge, &(polyb->p[0]), 
													&(polyb->p[j]));
					}
					else
					{
						statlseg_construct(&polybedge, &(polyb->p[j + 1]), 
													&(polyb->p[j]));
					}

					if (lseg_intersect_internal(&polybedge, &polyaedge))
					{
						result = true;
						break;
					}
				}

				if(result == true)
					break;
			}
		}
	}

	/*
	 * Avoid leaking memory for toasted inputs ... needed for rtree
	 * indexes
	 */
	PG_FREE_IF_COPY(polya, 0);
	PG_FREE_IF_COPY(polyb, 1);

	PG_RETURN_BOOL(result);

}


