// file: $isip/util/speech/isip_model_converter/imc_trans_0.cc
// version: $Id: imc_trans_0.cc 8977 2003-01-12 06:37:52Z jelinek $
//
// isip include files
//
#include "isip_model_converter.h"
 
// method: read_trans_cc
//
// arguments:
//  char_1* trans_file   : (input) data trans_file name
//  Vector<MatrixFloat>& : (output) transition map
//
// return: a boolean indicating status
//
// this method parses the prototype transitions file and builds a mapping
//
boolean read_trans_cc(char_1* trans_file_a,
		      Vector<MatrixFloat>& trans_matrices_a) {

  // open file
  //
  FILE* fp = fopen((char*)trans_file_a, "r");
  if (fp == (FILE*)NULL) {
    fprintf(stdout, "Cannot open file %s\n", trans_file_a);
    Integral::exit();
    return (float_4***)NULL;
  }
  
  // variables to read data
  //
  char_1* tmp = new char_1[File::MAX_FNAME_SIZE];
  int_4 num_states = (int_4)0;
  int_4 num_trans = (int_4)0;
  logical_1 number_flag = false;
  float_4 tmp_value = 0.0;
  
  // read data from file
  //
  while (fscanf(fp, "%s", tmp) != EOF) {

    // ignore comment lines
    //
    if (tmp[0] == (char_1)'#') {

      // do nothing
      //
      fscanf(fp, "%[^\n]", tmp);
      fscanf(fp, "%[\n]", tmp);
    }

    // read the transition matrix data
    //
    else if (strcmp((char*)tmp, (char*)IMC_STR_NUM_TRANSITIONS) == 0) {

      // change the flag
      //
      number_flag = true;
      
      // read the number of transitions
      //
      fscanf(fp, "%s", tmp);
      fscanf(fp, "%ld", &num_trans);

      // allocate space for the transitions
      //
      trans_matrices_a.setLength(num_trans);

      // now read the transitions data
      //
      for (int_4 i = 0; i < num_trans; i++) {
	
	// read the transition index and number of states
	//
	fscanf(fp, "%s%ld", tmp, &num_states);
	
	// allocate memory for the data
	//
	trans_matrices_a(i).setDimensions(num_states, num_states, false);

	// copy the transitions in
	//
	for (int_4 j = 0; j < num_states; j++) {

	  // read the transitions
	  //
	  for (int_4 k = 0; k < num_states; k++) {
	    fscanf(fp, "%f", &tmp_value);

	    trans_matrices_a(i).setValue(j, k, tmp_value);
	  }
	}
      } // end data loop
    } // end else if
  } // end while

  // check the flag 
  //
  if (number_flag == false) {
    fprintf(stdout, "Error : no number of transitions specified in %s\n",
	    (char*)trans_file_a);
    exit (Integral::exit());
  }
  
  // close file
  //
  fclose(fp);
    
  // free memory
  //
  delete [] tmp;
  
  // exit gracefully
  //
  return true;
}
