// file: ts_state_3.cc
//
// isip include files
//
#include "tie_state.h"
#include "tie_state_constants.h"

// method: print_ascii_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
//
logical_1 print_ascii_state_cc(char_1* file_a, State** states_a,
			       int_4 num_st_a, int_4 num_feat_a) {

  // open the file
  //
  FILE* fp = fopen((char*)file_a, "w");
  if (fp == (FILE*)NULL) {
    fprintf(stdout, "Cannot open output state file %s\n", file_a);
    exit(ISIP_PROTO_ERROR);
  }

  // output the comments
  //
  fprintf(fp, "%s\n", "# file : state.text");
  fprintf(fp, "%s\n", "#");
  fprintf(fp, "%s\n", "# data for acoustic models --- list of all the states that are tied");
  fprintf(fp, "%s\n\n", "#");

  // print number of states and vector size
  //
  fprintf(fp, "feature_size = %ld\n", num_feat_a);
  fprintf(fp, "num_states = %ld\n", num_st_a);
  
  // output the first state
  //
  fprintf(fp, "State: 0\n");
  fprintf(fp, "nummixes: 0\n\n");

  int_4 num_mixture = (int_4)0;
  float_4* temp_weight = (float_4*)NULL;
  float_4* temp_scale = (float_4*)NULL;
  float_4** tmp_mean = (float_4**)NULL;
  float_4** tmp_covar = (float_4**)NULL;
  
  for (int_4 i = 1; i < num_st_a; i++) {

    // get the parameters
    //
    num_mixture = states_a[i]->get_num_mixtures_cc();
    // num_mixture = (int_4)1;
    temp_weight = states_a[i]->get_weights_cc();
    temp_scale = states_a[i]->get_scale_cc();
    tmp_mean = states_a[i]->get_mean_cc();
    tmp_covar = states_a[i]->get_covar_cc();

    fprintf(fp, "State: %ld\n", i);
    fprintf(fp, "nummixes:  %ld\n\n", num_mixture);
    for (int_4 j = 0; j < num_mixture; j++) {
      fprintf(fp, "%s:  %ld\n", "mixture", j+1);
      fprintf(fp, "%s: %e\n", "mix_weight", exp(temp_weight[j]));
      fprintf(fp, "mean:   ");
      for (int_4 k = 0; k < num_feat_a; k++) {
	fprintf(fp, "%e ", tmp_mean[j][k]);
      }
      fprintf(fp, "\n");
      fprintf(fp, "covar:  ");
      for (int_4 l = 0; l < num_feat_a; l++) {
	fprintf(fp, "%e ", (float_4)1/tmp_covar[j][l]);
	}
      fprintf(fp, "\n");
      fprintf(fp, "scale:  %e\n\n", temp_scale[j]);
    }
  }

  // free memory
  //
  temp_weight = (float_4*)NULL;
  temp_scale = (float_4*)NULL;
  tmp_mean = (float_4**)NULL;
  tmp_covar = (float_4**)NULL;

  fclose(fp);
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
