/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split_MODIF.c                                   :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/11/13 07:08:40 by lperrey           #+#    #+#             */
/*   Updated: 2021/11/13 20:24:33 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

// FT_SPLIT LEGEREMENT REMANIER.
// A REMPLACER DANS LA LIBFT
#include "libft.h"

static size_t	count_word(char const *s, char c);
static char		**alloc_words(char const *s, char c, char **str_arr,
					size_t words_count);
static void		fill_arr(char const *s, char c, char **str_arr);

char	**ft_split(char const *s, char c)
{
	char	**str_arr;
	size_t	words_count;

	if (s == NULL)
		return (NULL);
	words_count = count_word(s, c);
	str_arr = ft_calloc(words_count + 1, sizeof(char *));
	if (!str_arr)
		return (NULL);
	if (!(alloc_words(s, c, str_arr, words_count)))
	{
		ft_free_2d_arr(str_arr);
		return (NULL);
	}
	fill_arr(s, c, str_arr);
	return (str_arr);
}

static size_t	count_word(char const *s, char c)
{
	unsigned int	i;
	size_t			count;

	count = 0;
	i = 0;
	while (s[i])
	{
		while (s[i] == c)
			i++;
		if (s[i])
			count++;
		while (s[i] && s[i] != c)
			i++;
	}
	return (count);
}

static char	**alloc_words(char const *s, char c, char **str_arr,
				size_t words_count)
{
	unsigned int	i;
	size_t			len;
	unsigned int	arr_i;

	i = 0;
	arr_i = 0;
	while (arr_i < words_count)
	{
		len = 0;
		while (s[i] == c)
			i++;
		while (s[i] && s[i] != c)
		{
			len++;
			i++;
		}
		str_arr[arr_i] = malloc(len + 1);
		if (!str_arr[arr_i])
			return (NULL);
		arr_i++;
	}
	return (str_arr);
}

static void	fill_arr(char const *s, char c, char **str_arr)
{
	unsigned int	i;
	unsigned int	arr_i;
	unsigned int	char_i;

	i = 0;
	arr_i = 0;
	while (str_arr[arr_i])
	{
		while (s[i] == c)
			i++;
		char_i = 0;
		while (s[i] && s[i] != c)
			str_arr[arr_i][char_i++] = s[i++];
		str_arr[arr_i][char_i] = '\0';
		arr_i++;
	}
}
