#include <helper.h>
#include <stdlib.h>

void str_list_init (struct str_list* this) {
  this->data = NULL;
  this->prev = NULL;
  this->next = NULL;
}

struct str_list* str_list_create (char* data) {
  struct str_list* retval = malloc(sizeof(*retval));
  if (retval == NULL) return NULL;
  str_list_init(retval);
  retval->data = data;
  return retval;
}

void str_list_destroy (struct str_list* this) {
  if (this) free(this);
}

void str_list_insert (struct str_list* entry, struct str_list* tail) {
  struct str_list* old_next = entry->next;

  tail = str_list_rewind(tail);

  if (entry) entry->next = tail;
  if (tail) tail->prev = entry;
  if (old_next) {
    while (tail->next != NULL) tail = tail->next;
    tail->next = old_next;
    old_next->prev = tail;
  }
}

struct str_list* str_list_append (struct str_list* list, struct str_list* tail) {
  if (list == NULL) return tail;
  if (tail == NULL) return list;

  while (list->next != NULL) list = list->next;
  str_list_insert(list,tail);
  return tail;
}

struct str_list* str_list_remove (struct str_list* element) {
  if (element == NULL) return NULL;
  if (element->next) element->next->prev = element->prev;
  if (element->prev) element->prev->next = element->next;
  return element;
}

struct str_list* str_list_rewind (struct str_list* list) {
  if (list == NULL) return NULL;
  while (list->prev != NULL) list = list->prev;
  return list;
}
