/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angoulem      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/10/05 19:04:34 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/06 19:33:51 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

void	*ft_cancel(char **tab, size_t len)
{
	size_t	i;

	if (tab != NULL)
	{
		i = 0;
		while (i < len)
		{
			free(tab[i]);
			i++;
		}
		free(tab);
	}
	return (NULL);
}

static size_t	ft_seglen(const char *s, char c)
{
	size_t	len;

	if (s == NULL)
		return (0);
	len = 0;
	while (*s != 0)
	{
		while (*s == c && *s != 0)
			s++;
		if (*s != 0)
			len++;
		while (*s != c && *s != 0)
			s++;
	}
	return (len);
}

static char	**ft_segsplitter(char **tab, size_t len, const char *s, char c)
{
	size_t	tab_index;
	size_t	let_index;
	size_t	start;

	tab_index = 0;
	let_index = 0;
	start = 0;
	if (tab == NULL || s == NULL)
		return (NULL);
	while (tab_index < len)
	{
		while (s[let_index] == c && s[let_index] != 0)
			let_index++;
		start = let_index;
		while (s[let_index] != c && s[let_index] != 0)
			let_index++;
		tab[tab_index] = ft_substr(s, start, let_index - start);
		if (tab[tab_index] == NULL)
			return (ft_cancel(tab, tab_index));
		tab_index++;
	}
	return (tab);
}

char	**ft_split(const char *s, char c)
{
	size_t	len;
	char	**tab;

	if (s == NULL)
		return (NULL);
	len = ft_seglen(s, c);
	tab = malloc((len + 1) * sizeof(char *));
	if (tab == NULL)
		return (NULL);
	tab[len] = NULL;
	if (ft_segsplitter(tab, len, s, c) == NULL)
		return (NULL);
	return (tab);
}
