// file: $USFS/class/image_analysis/v1.0/imaga_hist_03.cc
//

// system include files
//
#include <string.h>

// isip include files
//
#include "image_analysis.h"
#include <ppm.h>

#include "image_analysis_constants.h"

// method: hist_compute_cc
//
// arguments:
//  char_1* image_fname_a: (input) the image filename
//
// return: a logical_1 value indicating status
//
// this method computes a histogram on a PPM image file.
//
logical_1 Image_analysis::hist_compute_cc(char_1* image_fname_a) {
  
  // declare a ppm object
  //
  Ppm ppm;
  
  if (ppm.open_cc(image_fname_a, ISIP_READ_ONLY) == ISIP_FALSE) {
    error_handler_cc((char_1*)"hist_compute_cc",
		     (char_1*)"error opening the image file");
    return ISIP_FALSE;
  }
  
  // read the dimensions of the image
  //
  int_4 width = ppm.get_width_cc();
  int_4 height = ppm.get_height_cc();

  // initializing the block sizes
  //
  int_4 block_size = IMAGA_DEFAULT_BSIZE;
  int_4 actual_width = block_size;
  int_4 actual_height = block_size;
  
  uint_1 b_red[block_size*block_size];    // declaring the buffers for reading
  uint_1 b_green[block_size*block_size];  // the ppm image block by block
  uint_1 b_blue[block_size*block_size];
  
  // loop over all data
  //
  for (int_4 i=0; i<height; i+=block_size) {
    for (int_4 j=0; j<width; j+=block_size) {
      
      // checking for the out of bounds data
      //
      if ((j + block_size) >= width) {
	actual_width = width - j;
      }
      
      if ((i + block_size) >= height) {
	actual_height = height - i;
      }
      
      // read the ppm file block by block
      //
      if (ppm.read_cc(b_red, b_green, b_blue, j, i,
		       actual_width, actual_height) == ISIP_FALSE) {
	error_handler_cc((char_1*)"hist_compute_cc",
			 (char_1*)"error while reading the file");
	return ISIP_FALSE;
      }

      // compute the bins
      //
      if (hist_assign_cc(b_red, b_green, b_blue, j, i,
			 actual_width, actual_height) == ISIP_FALSE) {
	error_handler_cc((char_1*)"hist_compute_cc",
			 (char_1*)"error computing the bins");
	return ISIP_FALSE;
      }
    }
  }
  
  // close the ppm object
  //
  if (ppm.close_cc() == ISIP_FALSE) {
    error_handler_cc((char_1*)"hist_compute_cc",
		     (char_1*)"error closing the file");
    return ISIP_FALSE;
  }
  
  // increment counters
  //
  hist_t_nimages_d += (int_4)1;

  // exit gracefully
  //
  return ISIP_TRUE;
}
