// file: ts_model_3.cc
//

// system include files
//
#include <string.h>

// isip include files
//
#include "tie_state.h"
#include "tie_state_constants.h"

// method: write_cd_models_cc
//
// arguments:
//   FILE* fp_out_model : (input) file pointer to model file
//   int_4 num_mono : (input)  number of monophones
//   char_1** mono : (input)  monophone list
//   int_4 num_phy_models: (input) number of physical model
//   Cd_model** cd_models: all the models to be tied
//   int_4 num_cd_models: (input) number of all models to be tied
//   int_4* trans_map: (input) map of transition matrix index and central phone
//   Hast_table* table: (input) Hash_table showing if a model has been written 
//
// return: a logical_1 showing status
//
// this method loop through the 
//
logical_1 write_cd_models_cc(FILE* fp_out_model_a, int_4 num_mono_a,
			     char_1** mono_a, int_4 num_phy_models_a,
			     Cd_model** cd_models_a, int_4 num_cd_models_a,
			     int_4* trans_map_a, Hash_table* table_a) {
			    
  // define variables
  //
  int_4 num_states = 0;
  int_4* states_index;
  char_1** ph_names = (char_1**)NULL;;
  char_1* phone_name = new char_1[ISIP_MAX_STRING_LENGTH];
  int_4 num_models = 0;
  
  int_4 i;
  int_4 j;
  int_4 n_cph = (int_4)0;

  // add 2 to the number pf physical models to account for the dummy
  // sentence start and end phones
  // 
  fprintf(fp_out_model_a, "num_models = %ld\n\n", (num_phy_models_a));
    
  for(i = 0; i < num_cd_models_a; i++) {

    if (cd_models_a[i]->get_yesphy_cc() == ISIP_TRUE) {
      num_states = cd_models_a[i]->get_num_states_cc();
      states_index = cd_models_a[i]->get_states_ind_cc();
      
      ph_names = cd_models_a[i]->get_phones_cc();
      
      if (strcmp((char*)ph_names[0], (char*)TS_CDM_EMPTY_PHN) != 0) {
	strcpy((char*)phone_name, (char*)ph_names[0]);
	strcat((char*)phone_name, "-");
	strcat((char*)phone_name, (char*)ph_names[1]);
      }
      else {
	strcpy((char*)phone_name, (char*)ph_names[1]);
      }
      
      if (strcmp((char*)ph_names[2], (char*)TS_CDM_EMPTY_PHN) != 0) {
	strcat((char*)phone_name, "+");
	strcat((char*)phone_name, (char*)ph_names[2]);
      }
      
      for(j = 0; j < num_mono_a;  j++) {            
	if(strcmp((char*)ph_names[1], (char*)mono_a[j])==0) {
	  n_cph = j;
	  break;
	}
      }
      
      // print the physical model
      //     
      fprintf(fp_out_model_a, "index:  %ld\n", num_models);
      fprintf(fp_out_model_a, "phone:  %s\n", phone_name);
      fprintf(fp_out_model_a, "num_states:  %ld\n", (num_states+2));
      fprintf(fp_out_model_a, "transitions:  %ld\n", trans_map_a[n_cph]);
      fprintf(fp_out_model_a, "states:  0 ");
      for(j = 0; j < num_states; j++) {
	fprintf(fp_out_model_a, "%ld ", states_index[j]);
      }
      fprintf(fp_out_model_a, "0\n");
      fprintf(fp_out_model_a, "\n");
      num_models++;
    }
  }
  
  // free memory
  //
  delete [] phone_name;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
