/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   expander_parse_string.c                            :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/18 19:00:35 by qmennen       #+#    #+#                 */
/*   Updated: 2025/02/26 22:56:05 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static void	free_variables(t_minishell *msh, t_list *variables)
{
	t_list	*current;
	t_list	*last;

	current = variables;
	while (current)
	{
		last = current;
		current = current->next;
		free_safe(msh, (void **)&last);
	}
}

//TODO: Figure out why echo "> echo "\as"" breaks
char	*expander_parse_string(char *s, t_minishell *msh)
{
	t_list	*variables;
	t_list	*current;
	char	*string;
	int		i;
	int		j;

	variables = expander_parse_variables(s, msh);
	string = expander_allocate_memory(msh, s, variables);
	current = variables;
	i = 0;
	j = 0;
	while (s[i])
	{
		if (s[i] == '$' && s[i + 1] && current)
		{
			i++;
			i += expander_expand_dollar(s + i, string, &j, current);
			current = current->next;
		}
		else
			string[j++] = s[i++];
	}
	string[j] = 0;
	free_variables(msh, variables);
	return (string);
}
