// file: dtn_likelihood_5.cc
//

// isip include files
//
#include "dt_node.h"
#include "dt_node_constants.h"

// method:  compute_mean_cc
//                                            
// arguments:
//   float_4* mean: (output) the mean vector 
//   State** states: (input) all states associated with this node
//   float_4* occupy: (input) state occupancy
//   int_4 num_feat: (input) the number of features
//   int_4 num_mix: (input) the number of mixtures
//
// return: a logical_1 indicating status
//
logical_1 Dt_node::compute_mean_cc(float_4* mean_a, State** states_a,
				   float_4* occupy_a, int_4 num_feat_a,
				   int_4 num_mix_a) {
  
  // make sure memory is allocated for covariance vector
  //
  if(mean_a == (float_4*)NULL) {
    mean_a = new float_4[num_feat_a];
  }
  
  // local variables
  //
  float_4 sum_occupy = 0;
  float_4** s_mean = (float_4**)NULL;         // mean vector of state s
  
  // temporary array for computing the mean
  //
  float_4* tmp = new float_4[num_feat_a];  
  
  for(int_4 k=0;  k<num_feat_a; k++) {
    tmp[k] = 0.0;
    mean_a[k] = 0.0;
  }
  
  // compute sum of the states occupancy
  //
  for (int_4 i= 0; i<num_states_d; i++) {
    sum_occupy += occupy_a[state_index_d[i]];
  }
  
  if(sum_occupy != 0) {
    
    // loop all the states in this node, compute the covariance
    //
    for (int_4 i=0; i<num_states_d; i++) {
      
      s_mean = states_a[state_index_d[i]]->get_mean_cc();
      
      // for each state, loop all its mixtures and features
      //
      for (int_4 j=0; j<num_mix_a; j++) {
	
	for (int_4 k=0; k<num_feat_a; k++) {
	  tmp[k] += occupy_a[state_index_d[i]]*s_mean[j][k];
	}
      }
    } // end i
    
    // compute the mean
    //
    for (int_4 k=0; k<num_feat_a; k++) {
      mean_a[k] = tmp[k]/(float_4)sum_occupy;
    }
  }
  
  // free memory
  //
  delete [] tmp;
  
  return ISIP_TRUE;
}
