// find-max-points.c    Section: 10.3, Line Detection using the Hough Transform
//      Copyright 1994, Center for Computer Vision and Visualization,
//      University of Florida.  All rights reserved.

#include "find-max-points.h"


// This routine may find a few more points than asked because
//    it extracts the max image value at each iteration, and
//    then adds all points associated with that value.
// Hence it is possible to get more than you ask for.

template <class P, class T>
IA_Set<P>
find_max_points( const IA_Image<P,T> & image,
		 unsigned int & how_many ) {

    int hMin = min( image );

    int max_to_be_found = image.domain().card();

    if ( max_to_be_found < how_many ) {
	how_many = max_to_be_found;
	// They want all the points in the image....ok
	return
	    image.domain();
    }

    int found = 0;
    IA_Set<P> result( image.domain() / image.domain() ); // empty set
    IA_Set<T> vs( image.range() );

    while( ( ! vs.empty() ) &&
	   ( found < how_many ) ) {
	T maxval = vs.max();
	vs       = vs / maxval;               // No  vs /= maxval;
	IA_Set<T> maxvs( maxval );

	// There are points to add to the result;
	IA_Set<IA_Point<int> >
	    maxips( image.restrict( maxvs ).domain() );

	result |= maxips;
	found += maxips.card();
    }

    how_many = found;   // set the reference param return value
    return result;
}
