/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split_quoted.c                                  :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angoulem      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/10/05 19:04:34 by cchauvet          #+#    #+#             */
/*   Updated: 2023/02/15 14:25:56 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "utils.h"

size_t	ft_seglen_quoted(const char *str, char c)
{
	size_t	len;
	size_t	i;

	len = 0;
	i = 0;
	while (str[i] != 0)
	{
		while ((str[i] == c || ft_is_in_quote(str, i)) && str[i] != 0)
			i++;
		if (str[i] != 0)
			len++;
		while ((str[i] != c || ft_is_in_quote(str, i)) && str[i] != 0)
			i++;
	}
	return (len);
}

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

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

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

	if (s == NULL)
		return (NULL);
	len = ft_seglen_quoted(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);
}
