// file: cmmf_write_1.cc
//
 
// isip include files
//
#include "convert_mmf.h"
#include "convert_mmf_constants.h"
 
// method: write_states_ascii_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_ascii_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, "w");
  if (fp == (FILE*)NULL) {
    fprintf(stdout, "cannot open file %s\n", st_file_a);
    exit(ISIP_PROTO_ERROR);	
  }	
  
  // variables to write data
  //
  int_4 num_mix = (int_4)0;

  // output the feature size and number of states
  //
  fprintf(fp, "feature_size = %ld\n", num_feat_a);
  fprintf(fp, "num_states = %ld\n\n", num_st_a);

  // print the dummy 0'th state
  //
  fprintf(fp, "State: %ld\n", (int_4)0);
  fprintf(fp, "nummixes: %ld\n\n", (int_4)0);
    
  // 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
    //
    fprintf(fp, "State: %ld\n", i);
    num_mix = state_list_a[i]->get_num_mixtures_cc();
    fprintf(fp, "nummixes: %ld\n\n", num_mix);
    
    // loop over all mixtures and print the mixture weight, mean and
    // the variance
    //
    for (int_4 j = 0; j < num_mix; j++) {
      
      // print the mixture index
      //
      fprintf(fp, "mixture: %ld\n", j+1);
	  
      fprintf(fp, "mix_weight: %1.6e\n", st_mix_wt[j]);

      // print the mean vector
      //
      fprintf(fp, "mean: ");
      for (int_4 k = 0; k < num_feat_a; k++) {
	fprintf(fp, "%1.6e ", st_mix_mean[j][k]);
      }
      fprintf(fp, "\n");
      
      // print the variance vector
      //
      fprintf(fp, "covar: ");
      for (int_4 k = 0; k < num_feat_a; k++) {
	fprintf(fp, "%1.6e ", st_mix_covar[j][k]);
      }
      fprintf(fp, "\n");
      
      // print the scale factor
      //
      fprintf(fp, "scale: %1.6e\n\n", st_mix_scale[j]);
    }
  }
  
  // close output file
  //
  fclose(fp);
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
