#include "push_swap.h"

void	mark_sublist(t_stack *list)
{
	while (list && list->limit != 1)
	{
		if (list->limit == 2)
			list->limit = 0;
		else if (list->limit == 0)
			list->limit = 2;
		list = list->next;
	}
}

int	find_smallest(t_stack *list)
{
	int	i;
	int	smallest;
	int	position;

	smallest = list->n;
	position = 1;
	i = 0;
	while (list)
	{
		i++;
		if (list->limit == 2 && list->n < smallest)
		{
			smallest = list->n;
			position = i;
		}
		list = list->next;
	}
	if (i - position + 1 < position)
		position = position - i - 1;
	return (position);
}

void	sort_big(t_stack **a, t_stack **b, t_list *solution)
{
	int	list_size;
	int	next;
	int	i;

	list_size = sublist_size(*a);
	mark_sublist(*a);
	while (--list_size >= 0)
	{
		i = 0;
		next = find_smallest(*a);
		if (next > 0)
			while (++i < next)
				ra(a, &solution);
		else if (next < 0)
			while (i-- > next)
				rra(a, &solution);
		pb(b, a, &solution);
	}
	list_size = sublist_size(*b);
	while (list_size-- > 0)
		pa(a, b, &solution);
	mark_sublist(*a);
}
