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

#include "pslib.h"
#include "psAdditionals.h"

#include "papStuff.h"


static void memPrint(const psPtr ptr)
{
    psMemBlock *mb = ((psMemBlock*)ptr) - 1;
    printf("Memory block %lld (%lld):\n"
	   "\tFile %s, line %d, size %d\n"
	   "\tPosts: %x %x %x\n",
	   mb->id, mb->refCounter, mb->file, mb->lineno, mb->userMemorySize, mb->startblock, mb->endblock,
	   *(void**)((int8_t *)(mb + 1) + mb->userMemorySize));
}

// Split string on given characters
psList *papSplit(const char *string, const char *splitters)
{
    psList *values = psListAlloc(NULL);	// The list of values to return
    unsigned int length = strlen(string); // The length of the string
    unsigned int numSplitters = strlen(splitters); // Number of characters that might split
    unsigned int start = 0;		// The position of the start of a word
    for (int i = 1; i < length; i++) {
	bool split = false;		// Is this character a splitter?
	for (int j = 0; j < numSplitters && ! split; j++) {
	    if (string[i] == splitters[j]) {
		split = true;
	    }
	}
	if (split) {
	    if (i == start) {
		// Some idiot put in two spaces, or two commas or something
		start++;
	    } else {
		// We're at the end of the word
		psString word = psStringNCopy(&string[start], i - start);
		(void)psListAdd(values, PS_LIST_TAIL, word);
		start = i + 1;
		psFree(word);
	    }
	}
    }
    if (start < length) {
	// Copy the last word
	psString word = psStringNCopy(&string[start], length - start);
	(void)psListAdd(values, PS_LIST_TAIL, word);
	psFree(word);
    }

    return values;
}

