//
// mergeBoxes - merge overlapping boxes
//
// return 0 on success
//
int mergeBoxes(frame_t *frame)
{
    if (frame == NULL) {
        printf("ERROR: mergeBoxes called with frame == NULL\n");
        return 1;
    }
    
    box_t *temp1 = frame->boxes;
    box_t *temp2;
    box_t *temp3;
    int boxUpdated;
    boxUpdated = 1;

    while (boxUpdated) {    
        temp1 = frame->boxes;
        boxUpdated = 0;
        while (temp1 != NULL) {
            temp2 = temp1->next;
            while (temp2 != NULL) {
                if (boxesIntersect(temp1, temp2, 10)) {
                    // boxes intersect, merge them
                    int endy, endy1, endy2;
                    int endx, endx1, endx2;
                    endx1 = temp1->startx + temp1->width;
                    endx2 = temp2->startx + temp2->width;
                    endy1 = temp1->starty + temp1->height;
                    endy2 = temp2->starty + temp2->height;
                    
                    endx = MAX(endx1, endx2);
                    endy = MAX(endy1, endy2);
                    
                    int startx, starty;
                    startx = MIN(temp1->startx, temp2->startx);
                    starty = MIN(temp1->starty, temp2->starty);
                    
                    // expand the first box
                    temp1->startx = startx;
                    temp1->starty = starty;
                    temp1->width = endx - startx;
                    temp1->height = endy - starty;

                    // get the next pointer first before we delete it
                    temp3 = temp2->next;
                    
                    // delete the 2nd box
                    if (deleteBox(frame, temp2) != 0) {
                        printf("mergeBoxes: ERROR - could not delete box from frame\n");
                        return 1;
                    }
                    // update the temp2
                    temp2 = temp3;
                    // set the update flag so we rescan the boxes
                    boxUpdated = 1;
                } else {
                    temp2 = temp2->next;
                }
            }
            temp1 = temp1->next;
        }
    }
    return 0;
}
//---------------------------------------------------------------------------//
// Redistribute a set of range entity centroid coordinates with their owner
// ranks to the owning domain process.
void CoarseGlobalSearch::search( const EntityIterator& range_iterator,
				 const Teuchos::RCP<EntityLocalMap>& range_local_map,
				 const Teuchos::ParameterList& parameters,
				 Teuchos::Array<EntityId>& range_entity_ids,
				 Teuchos::Array<int>& range_owner_ranks,
				 Teuchos::Array<double>& range_centroids ) const
{
    // Assemble the local range bounding box.
    Teuchos::Tuple<double,6> range_box;
    assembleBoundingBox( range_iterator, range_box );

    // Find the domain boxes it intersects with.
    Teuchos::Array<int> neighbor_ranks;
    Teuchos::Array<Teuchos::Tuple<double,6> > neighbor_boxes;
    int num_domains = d_domain_boxes.size();
    for ( int n = 0; n < num_domains; ++n )
    {
	if ( boxesIntersect(range_box,d_domain_boxes[n],d_inclusion_tol) )
	{
	    neighbor_ranks.push_back(n);
	    neighbor_boxes.push_back( d_domain_boxes[n] );
	}
    }

    // For each local range entity, find the neighbors we should send it to.
    int num_neighbors = neighbor_boxes.size();
    EntityIterator range_begin = range_iterator.begin();
    EntityIterator range_end = range_iterator.end();
    EntityIterator range_it;
    Teuchos::Array<EntityId> send_ids;
    Teuchos::Array<int> send_ranks;
    Teuchos::Array<double> send_centroids;
    Teuchos::Array<double> centroid(d_space_dim);
    bool found_entity = false;
    for ( range_it = range_begin; range_it != range_end; ++range_it )
    {
	// Get the centroid.
	range_local_map->centroid( *range_it, centroid() );

	// Check the neighbors.
	found_entity = false;
	for ( int n = 0; n < num_neighbors; ++n )
	{
	    // If the centroid is in the box, add it to the send list.
	    if ( pointInBox(centroid(),neighbor_boxes[n],d_inclusion_tol) )
	    {
		found_entity = true;
		send_ids.push_back( range_it->id() );
		send_ranks.push_back( neighbor_ranks[n] );
		for ( int d = 0; d < d_space_dim; ++d )
		{
		    send_centroids.push_back( centroid[d] );
		}
	    }
	}

	// If we are tracking missed range entities, add the entity to the
	// list.
	if ( d_track_missed_range_entities && !found_entity )
	{
	    d_missed_range_entity_ids.push_back( range_it->id() );
	}
    }
    int num_send = send_ranks.size();
    Teuchos::Array<int> range_ranks( num_send, d_comm->getRank() );

    // Create a distributor.
    Tpetra::Distributor distributor(d_comm);
    int num_range_import = distributor.createFromSends( send_ranks() );

    // Redistribute the range entity ids.
    Teuchos::ArrayView<const EntityId> send_ids_view = send_ids();
    range_entity_ids.resize( num_range_import );
    distributor.doPostsAndWaits( send_ids_view, 1, range_entity_ids() );

    // Redistribute the range entity owner ranks.
    Teuchos::ArrayView<const int> range_ranks_view = range_ranks();
    range_owner_ranks.resize( num_range_import );
    distributor.doPostsAndWaits( range_ranks_view, 1, range_owner_ranks() );

    // Redistribute the range entity centroids.
    range_centroids.resize( d_space_dim*num_range_import );
    Teuchos::ArrayView<const double> send_centroids_view = send_centroids();
    distributor.doPostsAndWaits( 
	send_centroids_view, d_space_dim, range_centroids() );
}