// file: dec_read_8.cc
//
 
// isip include files
//
#include "decoder.h"
#include "decoder_constants.h"
 
// method: read_model_segment_cc
//
// arguments:
//  FILE* fp: (input) model-level alignment file pointer
//  
// return: a logical_1 indicating status
//
// this method reads in the model level segment information
//
logical_1 Decoder::read_model_segment_cc(FILE* fp_a) {

  // check file
  //
  if (fp_a == (FILE*)NULL) {
    error_handler_cc((char_1*)"read_model_segment_cc",
		     (char_1*)"NULL input file pointer");
  }

  
  // allocate segment list if one doesn't exist yet
  //
  if (model_seglist_d == (Link_list*)NULL) {
    model_seglist_d = new Link_list();
  }
  else {
    Link_node* nd = (Link_node*)NULL;
    Link_node* pd = (Link_node*)NULL;
    int_4* ele = (int_4*)NULL;
    
    for (nd = model_seglist_d->get_head_cc();
	 nd != (Link_node*)NULL; nd = pd) {
      pd = nd->get_next_cc();
      ele = (int_4*)(nd->get_item_cc());
      if (ele != (int_4*)NULL) {
	delete ele;
      }
      model_seglist_d->remove_cc(nd);
    }
    if (model_seglist_d != (Link_list*)NULL) {
      delete model_seglist_d;
      model_seglist_d = (Link_list*)NULL;
    }
  }
  
  // read the alignment file and get segments
  //
  int_4 tok_count = 0;
  int_4 end = (int_4)0;
  char* buf = (char*)NULL;
  char_1* str = new char_1[ISIP_MAX_STRING_LENGTH];
  while (fgets((char*)str, ISIP_MAX_STRING_LENGTH, fp_a) != (char*)NULL) {
    
    // tokenize the string
    //
    tok_count = 0;
    buf = strtok((char*)str, " ");

    while (buf != (char*)NULL) {
      buf = strtok((char*)NULL, " ");
      if (buf != (char*)NULL) {
	
	if (tok_count == 1) {
	  // do nothing
	  //
	}
	else if (tok_count == 0) {

	  // this is the endpoint for some model
	  //
	  end = (int_4)atoi(buf);

	  // insert this segmental information in the list
	  //
	  int_4* element = new int_4();
	  *element = end;
	  model_seglist_d->insert_cc(element);
	}
      }
      
      tok_count++;
    }
  }
  
  // exit gracefully
  //
  return ISIP_TRUE;
}
