#include "minishell.h"

static size_t count_parts(const char *s, char delim)
{
	size_t count = 0;
	int in = 0;
	while (*s)
	{
		if (*s == delim)
			in = 0;
		else if (!in)
		{
			in = 1;
			count++;
		}
		s++;
	}
	return count;
}

char **ms_split(const char *s, char delim)
{
	char **out;
	size_t parts;
	size_t i = 0;
	size_t start = 0;
	size_t len = 0;
	int in = 0;

	if (!s)
		return NULL;
	parts = count_parts(s, delim);
	out = (char **)calloc(parts + 1, sizeof(char *));
	if (!out)
		return NULL;
	while (s[i])
	{
		if (s[i] == delim)
		{
			if (in)
			{
				out[len++] = ms_strndup(s + start, i - start);
				in = 0;
			}
		}
		else if (!in)
		{
			in = 1;
			start = i;
		}
		i++;
	}
	if (in)
		out[len++] = ms_strndup(s + start, i - start);
	out[len] = NULL;
	return out;
}

void ms_free_split(char **sp)
{
	size_t i = 0;
	if (!sp)
		return;
	while (sp[i])
		free(sp[i++]);
	free(sp);
}
