// file: lat_wer_2.cc
//

// isip include files
//
#include "lattice.h"
#include "lattice_constants.h"

// method: add_path_cc
//
// arguments:
//  Link_list*& list: (input) the link lists to clean up
//  Link_node* marker: (input) the marker position in this list
//  Lattice_path* lpath: (input) the path to insert
//
// return: a logical_1 indicating status
//
// this method adds the given path to the list if it satisfies the
// dynamic programming constraints
//
logical_1 Lattice::add_path_cc(Link_list*& list_a, Link_node* marker_a,
			       Lattice_path* lpath_a) {

  // check if the list exists
  //
  if (list_a == (Link_list*)NULL) {
    list_a = new Link_list();
  }
  
  // otherwise need to loop through
  //
  else {

    // memory manager
    //
    Memory_manager* manager = Link_list::get_manager_cc();
    
    // start point for looping
    //
    Link_node* nd = (Link_node*)NULL;
    Link_node* snd = (Link_node*)NULL;
    
    // if the marker is null start at the head of list
    //
    if (marker_a == (Link_node*)NULL) {
      snd = list_a->get_head_cc();
    }
    else {
      snd = marker_a->get_next_cc();
    }
    
    // lattice path
    //
    Lattice_path* betr = (Lattice_path*)NULL;
    Lattice_path* lpath = (Lattice_path*)NULL;
    
    // loop over all nodes in the list
    //
    for (nd = snd; nd != (Link_node*)NULL; nd = nd->get_next_cc()) {
      
      // get the lattice path and compare it
      //
      lpath = (Lattice_path*)(nd->get_item_cc());
      betr = lpath_a->compare_cc(lpath);
      
      // check if comparison was successful
      //
      if (betr != (Lattice_path*)NULL) {
	
	// if the input path is better replace and return
	//
	if (betr == lpath_a) {
	  nd->set_item_cc(lpath_a);
	  manager->delete_cc(lpath);
	  return ISIP_TRUE;
	}
	
	// otherwise remove input path and return
	//
	else {
	  manager->delete_cc(lpath_a);
	  return ISIP_FALSE;
	}
      } // end if comparison successful
    } // end for loop over nodes
  } // end else
  
  // insert new path if we are here
  //
  list_a->insert_cc(lpath_a);
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
