#include <config.h>
#include <stdio.h>
#include <math.h>

#include "GFile.h"

/* GFile is an abstract decendant of GImage.  Derivatives of this class
 * represent various image file formats.  This class currently does not
 * add any new functionality.  It is reserved for future use.  Known
 * examples are:
 *
 *     GFile_TIFF
 *     GFile_JPEG
 *     GFile_KDC
 *
 * Written by:  Chris Studholme
 * Last Update: 6-December-1999
 * Copyright:   GPL (http://www.fsf.org/copyleft/gpl.html)
 */


/* ================ GFile methods  ================ */

void GFile::calculateBestMinMax(int& min, int& max, 
				unsigned int* histogram) {

  /*
    fprintf(stderr,"\nIndex:    ");
    for (int i=0; i<256; ++i)
    fprintf(stderr," %5d",i);
    fprintf(stderr,"\n");
    fprintf(stderr,"Histogram:");
    for (int i=0; i<256; ++i)
    fprintf(stderr," %5d",histogram[i]);
    fprintf(stderr,"\n");
  */

  min=0;
  max=255;
  unsigned int lcount = histogram[min];
  unsigned int hcount = histogram[max];
  unsigned int threshold=100;

  do {
    // adjust min
    if ((lcount+histogram[min+1])<threshold)
      lcount += histogram[++min];
    else if ((lcount>=threshold)&&(min>0))
      lcount -= histogram[min--];
    
    // adjust max
    else if ((hcount+histogram[max-1])<threshold)
      hcount += histogram[--max];
    else if ((hcount>=threshold)&&(max<255))
      hcount -= histogram[max++];
    
    else
      break;
    
  } while (true);
  
  //  fprintf(stderr,"Stats: %d %d %d\n",lcount,threshold,hcount);
}

void GFile::addToHistogram(unsigned int* histogram, 
			   unsigned char* array, int narray) {
  while (narray>0) {
    ++histogram[*array];
    ++array;
    --narray;
  }
}



