// file: dtn_split_0.cc
//

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

// method: split_node_cc
//
// arguments:
//   Question* question: (input) question to ask
//   Hash_table* answers: (input) Hash_table with all the answers
//   Dt_node* l_child: (output) the left child
//   Dt_node* r_child: (output) the right child
//   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 given a question 
//
logical_1 Dt_node::split_node_cc(Question* question_a, Hash_table* answers_a,
				 Dt_node* l_child_a, Dt_node* r_child_a,
				 int_4** l_context_a, int_4** r_context_a) {
  
  // local variables
  //
  int_4 i;
  int_4 l_count = 0;
  int_4 r_count = 0;
  int_4* map = new int_4[num_states_d];
  
  // intialize the map for answers of each state to a given question
  //
  for (i=0; i<num_states_d; i++) {
    map[i] = 0;
  }
  
  // variable for left child
  //
  int_4 l_num_states = 0;
  int_4* l_state_index;
  
  // variable for right child
  //
  int_4 r_num_states = 0;
  int_4* r_state_index;
  
  // loop all the states and find their answers to the given question
  //
  for(i=0; i<num_states_d; i++) {
    if(ask_question_cc(question_a, 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;
    }
  } 

  // if the states can be split according to this question
  //
  if(l_num_states>0 && r_num_states>0) {

    // set the states index for the new child nodes
    //
    l_state_index = new int_4[l_num_states];
    r_state_index = new int_4[r_num_states];
    
    for(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_a->set_states_cc(l_num_states, l_state_index);		     
    r_child_a->set_states_cc(r_num_states, r_state_index);
    
    // free memory
    //
    delete [] map;
    delete [] l_state_index;
    delete [] r_state_index;
    
    // exist gracefully
    //
    return ISIP_TRUE;
  }
  else {
    
    // free memory
    //
    delete [] map;
    
    // show that the node is not split
    //
    return ISIP_FALSE;
  }
}
