/** \file util.c -- utility functions
 * \copyright 2025 Matthias Andree, GNU GPL v2+
 */

#define _XOPEN_SOURCE 600
#include "util.h"
#include <string.h>

size_t str_split(char *str, const char *delim, char *outarray[], const size_t maxsplit, char **remainder)
{
        char *saveptr = NULL;
        char *startptr = str;
        char *curptr = NULL;
        size_t i;
        for (i = 0; i < maxsplit; ++i) {
                curptr = strtok_r(startptr, delim, &saveptr);
                outarray[i] = curptr;
                if (!curptr) break;
                startptr = NULL; // null this for subsequent strtok_r calls, which will look at saveptr
        }
        if (maxsplit == i && remainder && curptr) {
                *remainder = strtok_r(NULL, "", &saveptr);
        }
        return i;
}

bool str_startswith(const char *str /** string to check for \a prefix */, 
        const char *prefix /** prefix of string to check */)
{
        return 0 == strncmp(str, prefix, strlen(prefix));
}

#if defined(TEST)
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "xmalloc.h"

const char *program_name = "util";

static int test_split(int argc, char **argv) {
        int rc = EXIT_SUCCESS;
        for (int i = 0; i+2 < argc; i+=3) {
                char *endptr = NULL;
                errno = 0;
                unsigned long maxsplit = strtoul(argv[i+2], &endptr, 0);
                if (!maxsplit || ULONG_MAX == maxsplit || errno || *endptr || !*argv[i+2]) {
                        fprintf(stderr, "maxsplit invalid, skipping...\n");
                        rc = EXIT_FAILURE;
                        continue;
                }
                char **ary = (char **)xmalloc(sizeof(char *) * maxsplit);
                char *remainder = 0;
                size_t got = str_split(argv[i], argv[i+1], ary, maxsplit, &remainder);
                printf("str_split(\"%s\", \"%s\", ARRAY, %zu) returned %zu, remainder \"%s\"\n",
                        argv[i], argv[i+1], maxsplit, got, remainder ? remainder : "(NULL)");
                for (size_t j = 0; j < got; j++) printf("  %3zu %s\n", j, ary[j]);
                xfree(ary);
        }
        return rc;
}

int main(int argc, char **argv) {
        if (argc < 2) {
usage:
                fprintf(stderr, "Usage: %s SPLIT string delim num [...]\n", argv[0]);
                exit(EXIT_FAILURE);
        }
        if (!strcmp("SPLIT", argv[1])) return test_split(argc-2, argv+2); else goto usage;
}
#endif
