// file: normalize_features/nf_norm_0.cc
//

// local include files
//
#include "normalize_features.h"
#include "normalize_features_constants.h"

// function: accumulate_stats_cc
// 
// arguments:
//  float_8* mean_vector(output): the mean feature vector
//  float_8* sum_of_squares_vector(output): the vector that holds sum of
//                                          squares of each element
//  int_4& count (output): the accumulate count of feature vectors
//  int_4 num_coeffs (input): the number of coefficients in each feature vector
//  char_1* input_file (input): the input file name
//  int_4 input_format (input): the input file format( ascii or binary)
//
//  return value: a logical_1 indicating status
//
// this function gets the features vectors from the input file and accumulate
// them into the mean_vector and output the mean_vector and the total number
// of vectors
//
logical_1 accumulate_stats_cc(float_8* mean_vector_a,
			     float_8* sum_of_squares_vector_a, int_4& count_a,
			     int_4 num_coeffs_a, char_1* input_file_a,
			     int_4 input_format_a) {
  
  // local variables
  //
  float_8 input_vector[num_coeffs_a];
  float_8 tmp;
  
  // open the mfcc file
  //
  FILE* fmfc = fopen((char*)input_file_a, "r");
  if (fmfc == (FILE*)NULL) {
    fprintf(stdout, "Warning: cannot open file %s --> ", input_file_a);
    return ISIP_TRUE;
  }

  // ascii file
  //
  if (input_format_a == NF_IO_MODE_ASCII) {
    
    int_4 i = 0;
    while (fscanf(fmfc, "%lf", &tmp) != EOF) {

      // add to the mean vector and 
      // square the input element and add to
      // sum of squares vector
      //
      input_vector[i] = tmp;
      mean_vector_a[i] += input_vector[i];
      sum_of_squares_vector_a[i] += input_vector[i] * input_vector[i];
      i++;

      // increase the vector count
      //
      if (i >= num_coeffs_a) {
	i = i%num_coeffs_a;
	count_a++;
      }
    }

    // close file and exit gracefully
    //
    fclose(fmfc);
    return ISIP_TRUE;
  }
  
  // if binary mode, calculate the total number of features in this binary
  // mfcc file
  //
  int_4 num_vectors = 0;
  fseek(fmfc, 0, SEEK_END);
  int_4 file_size = ftell(fmfc);
  rewind(fmfc);
  num_vectors = file_size / num_coeffs_a / sizeof(float_8);
  
  // increase the vector count
  //
  count_a += num_vectors;
  
  for (int_4 i = 0; i < num_vectors; i++) {
    if (!fread(input_vector, sizeof(float_8), num_coeffs_a, fmfc)) {
      return ISIP_FALSE;
    }
    
    // add to the mean vector
    //
    for (int_4 j = 0; j < num_coeffs_a; j++) {
      mean_vector_a[j] += input_vector[j];
      sum_of_squares_vector_a[j] += input_vector[j] * input_vector[j];
    }
  }

  // close file and exit gracefully
  //
  fclose(fmfc);  

  return ISIP_TRUE;

}
