// file: tr_tok_trace_0.cc
//

// isip include files
//
#include "train_token.h"
#include "train_token_constants.h"
 
// method: insert_trace_cc
//
// arguments:
//  Train_Trace* trace : (input) the new trace to be added to list
//  float_8& score : (input) the max score so far
//
// return: a logical_1 indicating success
//
// this method adds the input trace to the list
//
logical_1 Train_Token::insert_trace_cc(Train_Trace* trace_a, float_8& score_a) {

  // dummy variables
  //
  float_8 score = (float_8)0;
  Train_Trace* tr = (Train_Trace*)NULL;
  Train_Trace* betr = (Train_Trace*)NULL;
  Train_Link_node* nd = (Train_Link_node*)NULL;
  Train_Memory_manager* manager = Train_Link_list::get_manager_cc();
  
  // check if any other traces exist already
  //
  if (trace_list_d == (Train_Link_list*)NULL) {
    trace_list_d = new Train_Link_list();
  }
  
  // set the insertion point
  //
  if (marker_d != (Train_Link_node*)NULL) {
    nd = marker_d->get_next_cc();
  }
  else {
    nd = trace_list_d->get_head_cc();
  }
  
  // insert only if this is better than existing traces
  //
  for (Train_Link_node* node = nd; node != (Train_Link_node*)NULL;
       node = node->get_next_cc()) {
    
    // get the trace in this node and compare with the input trace
    //
    tr = (Train_Trace*)(node->get_item_cc());
    betr = tr->compare_cc(trace_a);
    
    // if this was a valid comparison
    //
    if (betr != (Train_Trace*)NULL) {
      
      // update score
      //
      score = betr->get_score_cc();
      if (score > score_a) {
	score_a = score;
      }
      
      // if the input trace is the better path
      //
      if (betr == trace_a) {
	node->set_item_cc(trace_a);
	manager->delete_cc(tr);
      }
      
      // if the other trace is the better path
      //
      else {
	manager->delete_cc(trace_a);
      }
      
      // return with appropriate status
      //
      return ISIP_FALSE;
    }
  } // end for loop
  
  // otherwise insert trace
  //
  trace_list_d->insert_cc(trace_a);
  
  // update score
  //
  score = trace_a->get_score_cc();
  if (score > score_a) {
    score_a = score;
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
