#include <stdio.h>
#include <strings.h>
#include <glib.h>

#include "history.h"
#include "util.h"

HistoryNode *historynode_new(char *url)
{
  HistoryNode *h;

  h = (HistoryNode *)pmalloc(sizeof(HistoryNode), "HistoryNode");

  h->parent=NULL;
  h->sibling=NULL;
  h->descendent=NULL;

  strcpy(h->url, url);

  return h;
}
 
HistoryNode *historynode_add_descendent(HistoryNode *node, char *url)
{
  HistoryNode *h;

  h = historynode_new(url);
  h->parent = node;
  if(node) {
    h->sibling = node->descendent;
    node->descendent = h;
  }
  else {
    h->sibling=NULL;
  }

  return h;
}

/*HistoryNode *historynode_add_sibling(HistoryNode *node, char *url);*/

void historynode_remove_node(HistoryNode *node)
{
  HistoryNode *h, *a;

  h = node->parent;

  if(h) {
    if(h->descendent == node) {
      h->descendent = node->descendent;
      /* reparent each of node's children */
      for(h=h->descendent; h->sibling; h = h->sibling)
        h->parent = node->parent;
      h->sibling = node->sibling;
    } else {
      for(h=h->descendent; h->sibling != node; h = h->sibling);
      h->sibling = node->descendent;
      /* reparent each of node's children */
      for(h=h->sibling; h->sibling; h = h->sibling)
        h->parent = node->parent;
      h->sibling = node->sibling;
    }
  } else { /* removing an ancestor node */
    /* a is new ancestor node */
    if((a=node->descendent) != NULL) {
      for(h=a; h->sibling; h=h->sibling)
        h->parent = a;
      if((h=a->descendent)) {
        for(; h->sibling; h=h->sibling);
        h->sibling = a->sibling;
      } else {
        a->descendent = a->sibling;
      }
      a->sibling = NULL;
      a->parent = NULL;
    }
  }

  g_free(node);
  return;
}



