//#include <stdlib.h>
#include <stdio.h>
#include "psLib.h"


typedef struct { int i; } X;
static X *xAlloc(int i) { X *x = psAlloc(sizeof(X)); x->i = i; return x; }
static void xFree(X *x) { psFree(x); }

int main(void)
{
    psDlist *list = psDlistAlloc(NULL);	// list of metadata

    psDlistAppend(list, xAlloc(1));
    psDlistAppend(list, xAlloc(2));
    psDlistAppend(list, xAlloc(3));
    /*
     * Print that data
     */
    for (psDlistElem *ptr = list->head; ptr != NULL; ptr = ptr->next) {
	printf("%d ", ((X *)(ptr->data))->i);
    }
    printf("\n");
    /*
     * Print it again
     */
    (void)psDlistGet(list, PS_DLIST_TAIL); // initialise iterator
    X *x = NULL;
    while ((x = psDlistGet(list, PS_DLIST_PREV)) != NULL) {
	printf("%d ", x->i);
    }
    printf("\n");
#if 1
    /*
     * Convert to an array
     */
    psVector *arr = psDlistToArray(list);
    list = NULL;			// it\'s been freed

    for (int i = 0; i < arr->n; i++) {
	printf("%d ", ((X *)(arr->arr.arr_v[i]))->i);
    }
    printf("\n");
#if 1
    /*
     * Convert back to a list
     */
    list = psArrayToDlist(arr);
    arr = NULL;				// it\'s been freed

    (void)psDlistGet(list, PS_DLIST_TAIL); // initialise iterator
    while ((x = psDlistGet(list, PS_DLIST_PREV)) != NULL) {
	printf("%d ", x->i);
    }
    printf("\n");
#endif
    psVectorFree(arr, (void (*)(void *))xFree);
#endif

#if 1
    list = psArrayToDlist(psDlistToArray(list));

    (void)psDlistGet(list, PS_DLIST_TAIL); // initialise iterator
    while ((x = psDlistGet(list, PS_DLIST_PREV)) != NULL) {
	printf("%d ", x->i);
    }
    printf("\n");
#endif
    /*
     * Clean up
     */
    psDlistFree(list, (void (*)(void *))xFree);
    /*
     * Check for memory leaks
     */
    fprintf(stderr,"Checking for memory leaks:\n");
    psMemCheckLeaks(0, NULL, stderr);
    
    return 0;
}
