// file: $USFS/class/image_analysis/v6.2/imaga_he_04.cc
//

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

// method: seg_components_cc
//
// arguments: none
//
// return: a logical_1 value indicating status
//
// this method computes the mean vector and the covariance matrix for
// pca classification on the block level (for image segmentation)
//
logical_1 Image_analysis::seg_components_cc() {
  
  // perform the computation only for training mode
  //
  if ((mode_d == IMAGA_MODE_TRAIN) &&
      (algorithm_d == IMAGA_ALG_FACTOR)) {
    
    // compute the mean vector for the feature analysis
    //
    for (int_4 i=0; i<pca_t_values_read_d; i++) {
      mean_t_data_d[i] /= pca_t_nblks_d;
    }
    
    // subtract the mean to update the covariance matrix
    //
    for (int_4 i=0; i<pca_t_values_read_d; i++) {
      for (int_4 j=0; j <= i; j++) {
	covar_t_data_d[i*pca_t_values_read_d+j]
	  = (covar_t_data_d[i*pca_t_values_read_d+j] -
	     pca_t_nblks_d * mean_t_data_d[i] * mean_t_data_d[j]) / pca_t_nblks_d;
      }
    }
    
    // use the symmetry property for the remaining values of the 
    // covariance matrix
    //
    for (int_4 i=0; i < pca_t_values_read_d; i ++) {
      for (int_4 j=(i+1); j < pca_t_values_read_d; j++) {
	covar_t_data_d[i*pca_t_values_read_d+j] = 
	  covar_t_data_d[j*pca_t_values_read_d+i];
      }
    }
  }
  
  // debugging information
  //
  if (debug_level_d > ISIP_DEBUG_DETAILED) {
    
    // printing the  feature vector information
    //
    fprintf(stdout, "<Image_analysis::components_cc>\n");
    fprintf(stdout, "\n mean vector of the image\n");
    
    
    for (int_4 i=0; i < pca_t_values_read_d; i++) {
      fprintf(stdout, "%ld\t%f\n", i, mean_t_data_d[i]);
    }

    fprintf(stdout, "\n\n covariance matrix of the vector\n\n");
    
    for (int_4 i=0; i < pca_t_values_read_d; i++) {
      for (int_4 j=0; j < pca_t_values_read_d; j++) {
	fprintf(stdout, "%ld %ld %f\n", i, j, 
		covar_t_data_d[i*pca_t_values_read_d+j]);
      }
    }
  }
	
  // exit gracefully
  //
  return ISIP_TRUE;
}
