// file: bw_print_3.cc
//
// isip include files
//
#include "bw_train.h"
#include "bw_train_constants.h"

// method: print_bin_state_cc
//
// arguments:
//  char_1* file: (output) the new states file
//  State** states : (input) the new states need to be printed out
//  int_4 num_st : (input) the number of total states
//  int_4 num_feat : (input) the number of features
//
// return: a logical flag to indicate success
//

// this method writes the states in binary format into a new states
// file
//
logical_1 print_bin_state_cc(char_1* file_a, Train_State** states_a,
			     int_4 num_st_a, int_4 num_feat_a) {
  // local variables
  //
  int_4 num_mixture = (int_4)0;
  int_4 num_features = (int_4)0;
  float_4 temp_value = (float_4)0;
  float_4* tmp_weight = (float_4*)NULL;
  float_4* tmp_scale = (float_4*)NULL;
  float_4** tmp_mean = (float_4**)NULL;
  float_4** tmp_covar = (float_4**)NULL;
  
  // open the file
  //
  FILE* fp = fopen((char*)file_a, "wb");
  if (fp == (FILE*)NULL) {
    fprintf(stdout, "Cannot open output state file %s\n", file_a);
    fflush(stdout);
    exit(ISIP_PROTO_ERROR);
  }

  // print the initial state information
  //
  fwrite((void*)&num_feat_a, sizeof(int_4), 1, fp);
  fwrite((void*)&num_st_a, sizeof(int_4), 1, fp);

  // print all states
  //
  for (int_4 i = 0; i < num_st_a; i++) {
    
    // get the parameters
    //
    num_features = states_a[i]->get_num_features_cc();
    num_mixture = states_a[i]->get_num_mixtures_cc();
    tmp_weight = states_a[i]->get_weights_cc();
    tmp_scale = states_a[i]->get_scale_cc();
    tmp_mean = states_a[i]->get_mean_cc();
    tmp_covar = states_a[i]->get_covar_cc();
    
    //  output the number of mixtures
    //
    fwrite((void*)&num_mixture, sizeof(int_4), 1, fp);
    
    for (int_4 j = 0; j < num_mixture; j++) {
      
      // output the mixture weight
      //
      temp_value = exp(tmp_weight[j]);
      fwrite((void*)&temp_value, sizeof(float_4), 1, fp);
      
      // output the mean vector
      //
      for (int_4 k = 0; k < num_features; k++) {
	fwrite((void*)&tmp_mean[j][k], sizeof(float_4), 1, fp);
      }
      
      // output the covariance vector
      //
      for (int_4 l = 0; l < num_features; l++) {
	temp_value = 1.0/tmp_covar[j][l];
	fwrite((void*)&temp_value, sizeof(float_4), 1, fp);
      }
      
      // output the constant scale factor
      //
      fwrite((void*)&tmp_scale[j], sizeof(float_4), 1, fp);
    }
  }
  
  // free memory
  //
  tmp_weight = (float_4*)NULL;
  tmp_scale = (float_4*)NULL;
  tmp_mean = (float_4**)NULL;
  tmp_covar = (float_4**)NULL;

  // close the file
  //
  fclose(fp);
    
  // exit gracefully
  //
  return ISIP_TRUE;
}
