// file: bw_minlen_0.cc
//

// isip include files
//
#include "bw_train.h"
#include "bw_train_constants.h"

// method: get_minlen_cc
//
// arguments:
//  int_4& min_len : (output) the minimum length required to pass current model
//  Model* model : (input) the model object
//
// return: a logical_1 indicating success
//
// this method loop over all the possible path in current model and find the
// shortest path length
//
logical_1 get_minlen_cc(int_2& min_len_a, Train_Model* model_a) {

  // local variables
  //
  float_4* pre_states = (float_4*)NULL;
  float_4* cur_states = (float_4*)NULL;
  int_4 num_st = (int_4)0;
  float_4** trans = (float_4**)NULL;

  // get the states network information from the model objects
  //
  num_st = model_a->get_num_states_cc();
  trans = model_a->get_transitions_cc();

  // allocate memory for states status array
  //
  pre_states = new float_4[num_st];
  cur_states = new float_4[num_st];
  for (int_4 i = 0; i < num_st; i++) {
    pre_states[i] = (float_4)0.0;
    if (i != 0) {
      cur_states[i] = BW_LOG_ZERO;
    }
    else {
      cur_states[i] = log((float_8)1.0);
    }
  }
  
  // compute the shortest path by checking the transition matrix
  //
  for (int_4 k = 0; k < num_st; k++) {

    // update the status array
    //
    min_len_a = k;
    for (int_4 p = 0; p < num_st; p++) {
      pre_states[p] = cur_states[p];
      cur_states[p] = BW_LOG_ZERO;
    }
    
    // check the destination of all possible transitions if it reaches end
    // then exit
    //
    for (int_4 i = 0; i < num_st; i++) {

      // update the status of current states by valid transition
      //
      if (exp(pre_states[i]) > 0.0) {
	for (int_4 j = 0; j < num_st; j++) {
	  cur_states[j] = log_add_cc(cur_states[j], trans[i][j]);
	}
      }
    }

    // check the status of the last state
    //
    if ((exp(cur_states[num_st-1]) > (float_4)0.0)) {
      break;
    }
  }

  // clean up
  //
  delete [] pre_states;
  delete [] cur_states;
  trans = (float_4**)NULL;

  // exit gracefully
  //
  return ISIP_TRUE;
}
