// file: dtn_split_1.cc
//

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

// method: split_node_cc
//
// arguments:
//   Hash_table* answers: (input) Hash_table with all the answer
//   int_4** l_context: (input) the left contexts
//   int_4** r_context: (input) the right contexts
//
// return: a logical_1 indicating status
//
// this method splits the node using the optimal question 
//
logical_1 Dt_node::split_node_cc(Hash_table* answers_a, int_4** l_context_a,
				 int_4** r_context_a) {
  
  // local variables
  //
  int_4 l_count = 0;
  int_4 r_count = 0;
  int_4* map = new int_4[num_states_d];
  for(int_4 i=0; i<num_states_d; i++) {
    map[i] = 0;
  }
  
  l_child_d = new Dt_node();
  r_child_d = new Dt_node();
  l_child_d->set_parent_cc(this);
  r_child_d->set_parent_cc(this);
  
  // variables for the left child
  //
  int_4 l_num_states = 0;
  int_4* l_state_index;
  
  // variables for the right child
  //
  int_4 r_num_states = 0;
  int_4* r_state_index;
  
  // loop all the states and find their answers to the optimal question
  //
  for (int_4 i=0;i<num_states_d;i++) {
    if(ask_question_cc(opt_question_d,state_index_d[i], answers_a,
		       l_context_a, r_context_a) == ISIP_TRUE) {
      l_num_states +=1;
      map[i]= 1;
    }
    else {
      r_num_states +=1;
    }
  } 
  
  // set the state indices to the new child nodes
  //
  l_state_index = new int_4[l_num_states];
  r_state_index = new int_4[r_num_states];
  
  for(int_4 i=0;i<num_states_d;i++) {
    
    if(map[i] == 1) {
      l_state_index[l_count] = state_index_d[i];
      l_count += 1;
    }
    
    else {
      r_state_index[r_count] = state_index_d[i];
      r_count += 1;
    }
  }
  
  l_child_d->set_states_cc(l_num_states, l_state_index);		     
  r_child_d->set_states_cc(r_num_states, r_state_index);
  
  // update the leaf flag
  //
  set_leaf_flag_cc(ISIP_FALSE);
  l_child_d->set_leaf_flag_cc(ISIP_TRUE);
  r_child_d->set_leaf_flag_cc(ISIP_TRUE);

  // free memory
  //
  delete [] map;
  delete [] l_state_index;
  delete [] r_state_index;
  
  //exist gracefully
  //
  return ISIP_TRUE;
}






