// file: dec_index_0.cc
//

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

// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"
 
// method: get_model_index_cc
//
// arguments:
//  int_4* phn: (input) an array of ci phone indices
//  
// return: an int_4 with the cd model index
//
// this method finds the correct cd model index from the cd model map
// for the given sequence of ci models
//
int_4 Decoder::get_model_index_cc(int_4* phn_a) {

  // check argument
  //
  if (phn_a == (int_4*)NULL) {
    error_handler_cc((char_1*)"get_model_index_cc",
		     (char_1*)"NULL input array");
  }
  
  // dummy variables
  //
  int_4 index = (int_4)0;
  int_4 tmp = DEC_DEFAULT_INDEX;
  
  // for context-independent system
  //
  if (context_mode_d == DEC_MONO_PHONE_MODE) {
    
    // the index is the same as the phone
    //
    index = phn_a[0];
    
  } // end of monophone mode
  
  // otherwise this is context-dependent mode
  //
  else {
    
    // check the middle phone
    //
    tmp = phn_a[cd_size_d/2];
    if ((tmp == DEC_SILENCE_PHONE) || (tmp == DEC_SP_PHONE)) {
      index = tmp * (int_4)pow(num_ci_d, cd_size_d/2);
    }
    
    // otherwise loop over the constituent phone indices to determine
    // the location of the nphone
    //
    else {
      
      for (int_4 i = 0; i < cd_size_d - 1; i++) {
	tmp = phn_a[i];
	if (tmp <= DEC_SP_PHONE) {
	  tmp = (int_4)0;
	}
	index += tmp * (int_4)pow(num_ci_d, i);
      }
      if (phn_a[cd_size_d - 1] != DEC_SILENCE_PHONE ||
	  context_mode_d != DEC_WORD_INTERNAL_MODE) {
	tmp = phn_a[cd_size_d - 1];
	if (tmp <= DEC_SP_PHONE) {
	  tmp = (int_4)0;
	}
	index += tmp * (int_4)pow(num_ci_d, cd_size_d - 1);
      }
    }
  } // end if not monophone mode  
  
  // get the cd model index
  //
  int_4 model_index = cdmap_d[index];
  
  // make sure this model exists
  //
  if (model_index == DEC_DEFAULT_INDEX) {

    // generate an error mesage
    //
    char_1* mesg = new char_1[ISIP_MAX_STRING_LENGTH];
    strcpy((char*)mesg, "");
    
    // get the identity of the phone model
    //
    for (int_4 i = 0; i < cd_size_d/2; i++) {
      if (phn_a[i] > DEC_SP_PHONE) {
	strcat((char*)mesg, (char*)ci_models_d[phn_a[i]]);
	strcat((char*)mesg, (char*)"-");
      }
    }
    strcat((char*)mesg, (char*)ci_models_d[phn_a[cd_size_d/2]]);
    for (int_4 i = cd_size_d/2 + 1; i < cd_size_d; i++) {
      if (phn_a[i] > DEC_SP_PHONE) {
	strcat((char*)mesg, (char*)"+");
	strcat((char*)mesg, (char*)ci_models_d[phn_a[i]]);
      }
    }

    // print the phone string and free memory
    //
    fprintf(stdout, "%s ", (char*)mesg);
    delete [] mesg;
    
    // output an error message and exit
    //
    // error_handler_cc((char_1*)"get_model_index_cc",
    // (char_1*)"No model exists for this phone");
    printf("A model does not exist for this phone\n");
    model_index = 1;
  }
  
  // exit gracefully
  //
  return model_index;
}
