// file: normalize_features/nf_norm_1.cc
//

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

// function: normalize_features_cc
// 
// arguments:
//  float_8* out_vector (output): a big output feature vector
//  float_8* mean_vector (input): the mean feature vector
//  float_8* std_dev_vector (input): the vector that holds the global standard
//                                   deviation
//  int_4 num_coeffs (input): the number of coefficients of each feature vector
//  char_1* input_file (input): the input file name
//  int_4 num_vector (input): the number of vectors in this file
//  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 subtract
// mean from them and divides by the standard deviation amd outputs
// them as a big vector
//
logical_1 normalize_features_cc(float_8* out_vector_a, float_8* mean_vector_a,
			   float_8* std_dev_vector_a, int_4 num_coeffs_a,
			   char_1* input_file_a, int_4 num_vectors_a,
			   int_4 input_format_a) {

  // make sure the output memory is allocated
  //
  if (out_vector_a == (float_8*)NULL) {
    out_vector_a = new float_8[num_vectors_a * num_coeffs_a];
  }

  // lcoal variable to hold each vector
  //
  float_8 input_vector[num_coeffs_a];
  
  // 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;
  }
  
  // read the feature vectors
  //    
  for (int_4 i = 0; i < num_vectors_a; i++) {

    // read a feature vector
    //
    if (input_format_a == NF_IO_MODE_ASCII) {
      for (int_4 j = 0; j < num_coeffs_a; j++) {
	fscanf(fmfc, "%lf", &input_vector[j]);
      }
    }

    // binary mode
    //
    else {
      fread(input_vector, sizeof(float_8), num_coeffs_a, fmfc);
    }

    // normalize this vector
    //
    for (int_4 j = 0;  j < num_coeffs_a; j++) {

      // subtract the element from the global mean and divide
      // it by the global standard deviation to normalize it
      //
      if (std_dev_vector_a[j] != 0.0) {
	out_vector_a[i*num_coeffs_a + j] = (input_vector[j] - mean_vector_a[j])
	  / std_dev_vector_a[j];
      }
    }
  }
  
  // close file
  //
  fclose(fmfc);  

  // exit gracefully
  //
  return ISIP_TRUE;

}
