#include <stdio.h>
#include <string.h>
#include "taxon_tree.h"

taxon *find_taxon_item(taxon *head, char *name)
{
  taxon *ptr ;

  for (ptr = head ; 
       ptr != NULL && strcmp(name, ptr->name) ;
       ptr = ptr->next) ;

  return ptr ;
}

taxon *insert_taxon_item(taxon **head, char *name, void *other_data,
			 int replace_data)
{
  taxon *ptr, *newptr ;
  int new_entry = 1 ;

  if (*head == NULL ||
      strcmp(name, (*head)->name) < 0) {
    ptr = (taxon *)malloc(sizeof(taxon)) ;
    ptr->next = *head ;
    *head = ptr ;
  }
  else {
    for (ptr = *head ;
	 strcmp(name, ptr->name) &&
	   ptr->next != NULL &&
	   !(strcmp(name, ptr->next->name) < 0) ;
	 ptr = ptr->next) ;
    if (strcmp(name, ptr->name) > 0) {
      newptr = (taxon *)malloc(sizeof(taxon)) ;
      newptr->next = ptr->next ;
      ptr->next = newptr ;
      ptr = newptr ;
    }
    else new_entry = 0 ;
  }

  if (new_entry) {
    ptr->nextlevel = NULL ;
    strcpy(ptr->name, name) ;
    ptr->other_data = other_data ;
  }
  else if (replace_data) {
    free(ptr->other_data) ;
    ptr->other_data = other_data ;
  }

  return ptr ;
}

taxon *insert_taxon_child(taxon *parent, char *name, void *other_data,
			  int replace_data)
{
  taxon *ptr = NULL ;

  if (parent != NULL)
    ptr = insert_taxon_item(&(parent->nextlevel), name, other_data, 
			    replace_data) ;
  return ptr ;
}
