#include "push_swap.h"

// check more error
void	is_valid(int ac, char **av)
{
	if (ac < 2)
		ps_stop(NULL, NULL, 1);
	(void)av;
}

int	check_flag(int *ac, char ***av)
{
	if (ft_strcmp((*av)[1], "-p") == 0)
	{
		(*av)++;
		(*ac)--;
		return (1);
	}
	if (ft_strcmp((*av)[1], "-P") == 0)
	{
		(*av)++;
		(*ac)--;
		return (2);
	}
	return (0);
}

t_stack	*fill_stack(t_stack *list, char *nb)
{
	t_stack	*new;

	new = ft_calloc(1, sizeof(t_stack));
	if (!new)
		ps_stop(NULL, NULL, 2);
	new->n = ft_atoi(nb);
	new->limit = 0;
	new->next = list;
	list = new;
	return (list);
}

t_stack	*init_stack(int ac, char **av)
{
	char	**split;
	t_stack	*list;
	int		i;

	list = NULL;
	if (ac > 2)
		while (--ac)
			list = fill_stack(list, av[ac]);
	else if (ac == 2)
	{
		split = ft_split(av[1], ' ');
		i = 0;
		while (split[i] != NULL)
			i++;
		while (--i >= 0)
			list = fill_stack(list, split[i]);
	}
	return (list);
}

/*
** the chained list "solution" is created with specials first two elements :
** they are pointers to stack a and b, so it can be accessed by fill_solution()
*/
t_list	*launch_algo(t_stack **a, t_stack **b, int flag)
{
	t_list		*solution;

	solution = ft_lstnew(a);
	ft_lstadd_back(&solution, ft_lstnew(b));
	if (flag)
	{
		fill_solution(solution, "start");
		mark_step(solution, "start");
	}
	hugo_sort(a, b, solution);
//	bubble_sort(a, b, solution);
	return (solution);
}

int	main(int ac, char **av)
{
	t_stack		*a;
	t_stack		*b;
	t_list		*solution;
	int			flag;

	is_valid(ac, av);
	flag = check_flag(&ac, &av);
	a = init_stack(ac, av);
	b = NULL;
	solution = launch_algo(&a, &b, flag);
	print_result(solution, flag);
	ps_stop(NULL, solution, 0);
	return (0);
}
