// file: cmmf_write_2.cc
//
 
// isip include files
//
#include "convert_mmf.h"
#include "convert_mmf_constants.h"
 
// method: write_states_bin_cc
//
// arguments:
//  int_4 num_st : (input) number of states
//  int_4 num_feat : (input) number of features in data vector
//  char_1* st_file : (input) data file name
//  State** state_list: (input) list of states
//
// return: a State** pointing to a list of States
//
// this method writes the State file --- each mixture
// component in the States is assumed to have a diagonal covariance
// matrix
//
logical_1 write_states_bin_cc(int_4 num_st_a, int_4 num_feat_a,
			      char_1* st_file_a, Train_State** state_list_a) {
  
  // open file for writing
  //
  FILE* fp = fopen((char*)st_file_a, "wb");
  if (fp == (FILE*)NULL) {
    fprintf(stdout, "cannot open file %s\n", st_file_a);
    exit(ISIP_PROTO_ERROR);	
  }	
  
  // variables to read data
  //
  int_4 num_mix = (int_4)0;

  // output the feature size and number of states
  //
  fwrite((void*)&num_feat_a, sizeof(int_4), 1, fp);
  fwrite((void*)&num_st_a, sizeof(int_4), 1, fp);

  // print the dummy 0'th state
  //
  fwrite((void*)&num_mix, sizeof(int_4), 1, fp);    

  // for each state print the contents
  //
  for (int_4 i = 1; i < num_st_a; i++) {

    // get the state information 
    //
    float_4* st_mix_wt = state_list_a[i]->get_weights_cc();
    float_4** st_mix_mean = state_list_a[i]->get_mean_cc();
    float_4** st_mix_covar = state_list_a[i]->get_covar_cc();
    float_4* st_mix_scale = state_list_a[i]->get_scale_cc();
    
    // print number of mixtures in the state
    //
    num_mix = state_list_a[i]->get_num_mixtures_cc();
    fwrite((void*)&num_mix, sizeof(int_4), 1, fp);    

    // loop over all mixtures and print the mixture weight, mean and
    // the variance
    //
    for (int_4 j = 0; j < num_mix; j++) {
    fwrite((void*)&st_mix_wt[j], sizeof(float_4), 1, fp);

      // print the mean vector
      //
      for (int_4 k = 0; k < num_feat_a; k++) {
	fwrite((void*)&st_mix_mean[j][k], sizeof(float_4), 1, fp);	
      }

      // print the variance vector
      //
      for (int_4 k = 0; k < num_feat_a; k++) {
	fwrite((void*)&st_mix_covar[j][k], sizeof(float_4), 1, fp);
      }

      // print the scale factor
      //
      fwrite((void*)&st_mix_scale[j], sizeof(float_4), 1, fp);
    }
  }
  
  // close output file
  //
  fclose(fp);
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
