
#include "push_swap.h"

/*
** this function check errors in the arguments
** like, is there arguments, and are they a valid list without equals values
** if there are no arguments it calls the stop function with value 1 to print usage
*/
void	is_valid(int ac, char **av)
{
	if (ac < 2)
		ps_stop(NULL, NULL, NULL, 1);
	(void)av;
	// check more error
}

/*
** this function check if there are flags (currently only one flag) :
** -p to print the evolution of the list while the sorting is done
*/
int		check_flag(int *ac, char ***av)
{
	if (ft_strcmp((*av)[1], "-p") != 0)
		return (0);
	(*av)++;;
	(*ac)--;
	return (1);
}

/*
** create the stack for list a, as a linked list, and fill it with the values given in arguments argv
*/
t_stack	*init_stack(int ac, char **av)
{
	t_stack		*start;
	t_stack		*tmp;

	tmp = NULL;
	while (--ac)
	{
		if (!(start = ft_calloc(1, sizeof(t_stack))))
			ps_stop(start, NULL, NULL, 2);
		start->n = ft_atoi(av[ac]);
		start->next = tmp;
		tmp = start;
	}
	return (start);
}

/*
** this function creates the stack b and the list solution
** then it init the list solution with initial values of stack a (in case of flag -p)
** then it calls the sorting algorithm
** then it calls ps_stop() to free everything that needs to be freed
*/
t_list	*launch_algo(t_stack *a)
{
	t_stack		*b;
	t_list		*solution;

	if(!(b = ft_calloc(1, sizeof(t_stack))))
		ps_stop(a, b, NULL, 2);
	solution = NULL;
	fill_solution(a, NULL, &solution, ft_strdup("start"));
	hugo_sort(&a, &b, &solution);
	ps_stop(NULL, b, NULL, -1);
	return (solution);
}

/*
** this programme will sort a list
** this function first check the validity of the arguments
** then it checks for flags (currently only -p)
** then it parse the list into a linked list
** then it calls the sorting algorithm (it actually calls a launch function that will execute some actions and calls the sorting algorithm)
** and finally it frees everything and leaves
*/
int		main(int ac, char **av)
{
	t_stack		*stack;
	t_list		*result;
	int			flag;

	is_valid(ac, av);
	flag = check_flag(&ac, &av);
	stack = init_stack(ac, av);
	result = launch_algo(stack);
	print_result(result, flag);
	ps_stop(stack, NULL, result, 0);
	return(0);
}
