// global-threshold.c   Section: 3.2
//      Copyright 1994, Center for Computer Vision and Visualization,
//      University of Florida.  All rights reserved.

// This application actually will do several types of thresholding:
//
//      Threshold on a single value.
//      Threshold on an interval of values.
//      Threshold over a percentage of values.

#include "Set.h"
#include "UcharDI.h"

void main( int argc, char * argv[] ) {

    if ( argc == 1 ) {
	cerr << "Usage: 3 ways to threshold" << endl
	     << "  " << argv[0]
	     << " threshold-value < inImage > outImage ; absolute threshold"
	     << endl << "- OR -" << endl
	     << "  " << argv[0]
	     << " start end < inImage > outImage ; threshold on interval"
	     << endl << "- OR -" << endl
	     << "  " << argv[0]
	     << " real-value < inImage > outImage ; Percentage threshold ***"
	     << endl;
	cerr << "\t*** Note: threshold-value < 1.0 => percentage threshold."
	     << endl;
	return ;
    }


    IA_Image<IA_Point<int>,u_char> image( read_uchar_PGM( cin ) );
    u_char  mn( min( image ) ), mx( max( image ) );
    if ( ! image.domain().empty() ) {
	cerr << "cin image min: "  << int( mn )
	     << ", max: " << int( mx ) << endl;
    }


    double arg( atof( argv[1] ) );

    u_char
	start( u_char( arg ) ),  // A good guess as the the starting value
	end;

    cerr << endl;
    if (arg < 1.0) {  // Percentage threshold
	double  dthreshold( arg * (mx - mn) );

	start = u_char( dthreshold );
	end   = mx;

	cerr << "Percentage threshold on: ";
    } else if (argc == 2 ) {	// Value threshold
	end   = start;
	cerr << "\nValue thresholding on: " ;
    } else {	// Value interval threshold
	end = u_char( atoi( argv[2] ) );
	if (end < start) {
	    u_char t(end); end = start; start = t;
	}
	cerr << "\nInterval thresholding on: ";
    }

    u_char * interval = new u_char[end - start + 1];
    for( u_char u=start; u<=end; u++ ) {
	interval[ u-start ] = u;
    }
    IA_Set<u_char>
	threshold_set( interval,
		       (unsigned int)(end - start + 1) );
    delete[] interval;

    cerr << "[" << int( start ) 
	 << "," << int( end ) << "]" << endl;
    image =
	IA_Image<IA_Point<int>,u_char>(
	    chi_contains( image, threshold_set ) );

    image.write_PGM( cout );
}
