#include "double.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

struct dlist *dlist_append(struct dlist *l, int e)
{
    struct dlist *new_node = calloc(1, sizeof(struct dlist));
    if(!new_node) return NULL;

    new_node->prev = NULL;
    new_node->next = l;
    new_node->data = e;

    if (l) l->prev = new_node;

    return new_node;

}

int dlist_insert(struct dlist **l, size_t index, int e)
{
    if(!l) return 1;

    //struct dlist *new_node = malloc(sizeof(struct dlist));
    //if(!new_node) return 1;

    //struct dlist *tmp = *l;

    if(index == 0){ 
        
        *l = dlist_append(*l, e);
        if(!l) return 1;
        return 0;
    }

    struct dlist *tmp = *l;
    size_t ind = 0;
    while(tmp != NULL && ind < index - 1){

        tmp = tmp->next;
        ind ++;
    }

    if(!tmp) return 1;

    struct dlist *new_node = malloc(sizeof(struct dlist));
    if(!new_node) return 1;

    new_node->data = e;
    new_node->next = tmp->next;
    new_node->prev = tmp;

    if (tmp->next != NULL) tmp->next->prev = new_node;
    tmp->next = new_node;

    return 0;

}

struct dlist *dlist_delete_at(struct dlist **l, size_t index)
{
    if(!l || *l) return NULL;

    struct dlist *old = NULL;
    if(index == 0){

        old = *l;
        *l = old->next;
        
        return old;
    }

    struct dlist *tmp = *l;
    size_t ind = 0;
    while(tmp != NULL && ind < index -1){
        
        tmp = tmp->next;
        ind ++;
    }



    if(ind == index -1){

        old = tmp->next;
        tmp->prev = old->prev;
        tmp->next = old->next;
        
        return old;
    }

    return NULL;
}

int dlist_remove(struct dlist **l, int e)
{
    struct dlist *old = NULL;
    struct dlist *tmp = *l;

    while(tmp != NULL && tmp->data != e){

        old = tmp;
        tmp = tmp->next;
    }

    if(!tmp) return 0;

    if(!old){

        *l = tmp->next;
    }
    else {

        old->next = tmp->next;
        old->prev = tmp->prev;
    }

    free(tmp);

    return 1;
}

void dlist_print(struct dlist *l)
{
    
    struct dlist *tmp = l;

    while (tmp != NULL){

        printf("%i", tmp->data);

        if (tmp->next != NULL) printf(" <-> ");

        tmp = tmp->next;
    }

    printf("\n");

}
