// file: dec_read_2.cc
//
 
// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"
 
// method: read_hmms_cc
//
// arguments:
//  FILE* fp: (input) file pointer
//  
// return: a logical_1 indicating status
//
// this method reads in the HMM data from file into an array of model
// objects
//
logical_1 Decoder::read_hmms_cc(FILE* fp_a) {

  // check file
  //
  if (fp_a == (FILE*)NULL) {
    error_handler_cc((char_1*)"read_hmms_cc",
		     (char_1*)"NULL input file pointer");
  }
  
  // variables to read data
  //
  char_1* tmp = new char_1[ISIP_MAX_STRING_LENGTH];
  char_1* name = new char_1[ISIP_MAX_STRING_LENGTH];
  State** state_list = (State**)NULL;

  int_4 num_states = (int_4)0;
  int_4 model_ind = (int_4)0;
  int_4 trans_ind = (int_4)0;
  int_4 state_ind = (int_4)0;
  
  // read data from file
  //
  while (fscanf(fp_a, "%s", tmp) != EOF) {
    
    // ignore comment lines
    //
    if (tmp[0] == (char_1)'#') {
      
      // do nothing
      //
      fscanf(fp_a, "%[^\n]", tmp);
      fscanf(fp_a, "%[\n]", tmp);
    }
    
    // read the model data
    //
    else if (strcmp((char*)tmp, "num_models") == 0) {
      
      // read the number of models
      //
      fscanf(fp_a, "%s%ld", tmp, &num_models_d);
      
      // allocate space for the model list
      //
      models_d = new Model*[num_models_d];
      
      // now read the model data
      //
      for (int_4 i = 0; i < num_models_d; i++) {
	
	// read the model index
	//
	fscanf(fp_a, "%s%ld", tmp, &model_ind);
	
	// read the model string
	//
	fscanf(fp_a, "%s%s", tmp, name);
	
	// read the number of states
	//
	fscanf(fp_a, "%s%ld", tmp, &num_states);
	
	// allocate memory for the data
	//
	state_list = new State*[num_states];
	
	// read the transitions
	//
	fscanf(fp_a, "%s%ld", tmp, &trans_ind);
	
	// read the states
	//
	fscanf(fp_a, "%s", tmp);
	for (int_4 j = 0; j < num_states; j++) {
	  
	  // read the state index
	  //
	  fscanf(fp_a, "%ld", &state_ind);
	  
	  // add to the state array
	  //
	  if (state_ind == 0) {
	    state_list[j] = (State*)NULL;
	  }
	  else {
	    state_list[j] = states_d[state_ind];
	  }
	}

	// create the model
	//
	models_d[model_ind] = new Model(num_states, transitions_d[trans_ind],
					state_list);

	// free memory
	//
	delete [] state_list;
	state_list = (State**)NULL;
      }
    } // end else if
  } // end while

  // free memory
  //
  delete [] tmp;
  delete [] name;
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
