/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/15 14:22:44 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:04:27 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

static int	free_if_failed(char **split, int index)
{
	int	i;

	if (index < 0)
		return (0);
	if (!split)
		return (1);
	if (split[index])
		return (0);
	i = 0;
	while (split[i])
	{
		free(split[i]);
		i++;
	}
	free(split);
	return (1);
}

static int	ft_count_str(const char *str, char c)
{
	int	count;
	int	i;
	int	sub_str_start;

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

static char	*ft_str_dup_range(const char *str, int start_index, int end_index)
{
	char	*dup;
	int		i;

	dup = malloc(sizeof(char) * (end_index - start_index + 1));
	if (!dup)
		return (0);
	i = 0;
	while (i < (end_index - start_index))
	{
		dup[i] = str[start_index + i];
		i++;
	}
	dup[i] = '\0';
	return (dup);
}

static void	init_to_zero(int *sub_str_start, int *index_str, int *i)
{
	*sub_str_start = 0;
	*index_str = 0;
	*i = 0;
}

//returns NULL if s is NULL or if any allocation fails
char	**ft_split(char const *s, char c)
{
	char	**tab;
	int		sub_str_start;
	int		index_str;
	int		i;

	if (!s)
		return (NULL);
	init_to_zero(&sub_str_start, &index_str, &i);
	tab = malloc(sizeof(char *) * (ft_count_str(s, c) + 1));
	if (!tab)
		return (NULL);
	while (s[i])
	{
		while (s[i] && (s[i] == c))
			i++;
		sub_str_start = i;
		while (s[i] && (s[i] != c))
			i++;
		if (sub_str_start < i)
			tab[index_str++] = ft_str_dup_range(s, sub_str_start, i);
		if (free_if_failed(tab, index_str - 1))
			return (NULL);
	}
	tab[index_str] = 0;
	return (tab);
}
