// file: itri_read_3.cc
//
// isip include files
//
#include "init_triphones.h"
#include "init_triphones_constants.h"
 
// method: read_cimodels_cc
//
// arguments:
//  FILE* fp_in : (input) data file pointer
//  int_4& num_mono : (output) number of monophones
//  
// return: a a pointer to Hash_table with ci phones
//
Train_Hash_table* read_cimodels_cc(FILE* fp_in_a, int_4& num_mono_a) {

  // variables to read data
  //
  char_1* tmp = new char_1[ISIP_MAX_STRING_LENGTH];
  char_1* mphones = (char_1*)NULL;
  Train_Hash_cell* ph_cell = (Train_Hash_cell*)NULL;
  Train_Hash_table* phone_table = (Train_Hash_table*)NULL;
  phone_table = new Train_Hash_table(TRAIN_HASH_TABLE_SIZE);
  logical_1 number_flag = ISIP_FALSE;

  // define memory manager
  //
  Train_Memory_manager* manager = Train_Link_list::get_manager_cc(); 

  // read data from file
  //
  while (fscanf(fp_in_a, "%s", tmp) != EOF) {
    
    // ignore comment lines
    //
    if (tmp[0] == (char_1)'#') {
      
      // do nothing
      //
      fscanf(fp_in_a, "%[^\n]", tmp);
      fscanf(fp_in_a, "%[\n]", tmp);
    }
    
    // read the monophone data
    //
    else if (strcmp((char*)tmp, (char*)ITRI_STR_NUM_MONOPHONES) == 0) {

      // check the flag
      //
      number_flag = ISIP_TRUE;
      
      // read the number of monophones
      //
      fscanf(fp_in_a, "%s", tmp);
      fscanf(fp_in_a, "%ld", &num_mono_a);
      
      // now read the monophone data
      //
      for (int_4 i = 0; i < num_mono_a; i++) {
	
	// read the monophone string and copy it
	//
	fscanf(fp_in_a, "%s", tmp);
	mphones = new char_1[strlen((char*)tmp) + 1];
	strcpy((char*)mphones, (char*)tmp);

	// insert into hash table
	//
	ph_cell = manager->new_hash_cc();
	ph_cell->set_cc(mphones, (void_p)i);
	phone_table->hash_insert_cc(ph_cell);
	delete [] mphones;	
      }
    }
  }

  // check the flag
  //
  if (number_flag == ISIP_FALSE) {
    fprintf(stdout, "Error : no number of monophones specified.\n");
    exit(ISIP_PROTO_ERROR);
  }
  
  // free memory
  //
  delete [] tmp;
  
  // exit gracefully
  //
  return phone_table;
}
