// file: $USFS/class/image_analysis/v3.0/imaga_he_07.cc
//

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

// isip include files
//
#include "image_analysis.h"
#include "image_analysis_constants.h"

// method: pca_compare_cc
//
// arguments:
// float_8& sbe_value: (output) scenic beauty rating
//
// return: a logical_1 value indicating status
//
// this method trains on the images to output the histogram and the edge
// detection as a feature vector
//
logical_1 Image_analysis::pca_compare_cc(float_8& sbe_a) {

  // declare local variables
  //
  float_8* tmp_buf = new float_8[pca_t_values_read_d];
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    tmp_buf[i] = 0.0;
  }

  // allocate memory and initialize to zero
  //
  float_8* inter_matrix = new float_8[pca_t_values_read_d];
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    inter_matrix[i] = 0.0;
  }
  
  // reading the covariance data
  //
  float_8** tmp_data = new float_8*[pca_t_values_read_d];
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    tmp_data[i] = new float_8[pca_t_values_read_d];
    memset((void*)tmp_data[i], (int)0, pca_t_values_read_d);
  }
  
  // reading the data into a two dimensional form
  //
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    for (int_4 j=0; j < pca_t_values_read_d; j++) {
      tmp_data[i][j] = covar_t_data_d[i*pca_t_values_read_d + j];
    }
  }
  
  // compute the inverse of the covariance_matrix
  //
  if (pca_inverse_cc(tmp_data) == ISIP_FALSE) {
    error_handler_cc((char_1*)"pca_compare_cc",
		     (char_1*)"error computing the inverse matrix");
    return ISIP_FALSE;
  }
  
  // computing the diff of the feature and the mean vector
  //
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    tmp_buf[i] = pca_t_data_d[i] - mean_t_data_d[i];
  }
  
  // computing the product of the inverse of the matrix with the
  // diff of the feature and the mean vector
  //
  for (int_4 j=0; j < pca_t_values_read_d; j++) {
    for (int_4 m=0; m < pca_t_values_read_d; m++) {
      inter_matrix[j] += tmp_buf[m] * tmp_data[m][j];
    }
  }
  
  // computing the final distance
  //
  for (int_4 i=0; i < pca_t_values_read_d; i++) {
    sbe_a += inter_matrix[i] * tmp_buf[i];
  }
  
  // finding the square root for the distance
  //
  sbe_a = sqrt(fabs(sbe_a));
  
  // delete the buffers
  //
  delete [] tmp_buf;
  delete [] inter_matrix;

  for (int_4 i = 0; i < pca_t_values_read_d; i++) {
    delete [] tmp_data[i];
  }
  delete[] tmp_data;
  
  // debugging information
  //
  if (debug_level_d > ISIP_DEBUG_DETAILED) {
    
    // printing the  feature vector information
    //
    fprintf(stdout, "<Image_analysis::pca_compare_cc>\n");
    fprintf(stdout, "\n sbe of the image\n");
    
    fprintf(stdout, "%f\n", sbe_a);
  }

  // exit gracefully
  //
  return ISIP_TRUE;
}
