/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_x_case.c                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pbonilla <eirodeis.lepnj@gmail.com>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/03/08 16:22:32 by pbonilla          #+#    #+#             */
/*   Updated: 2021/03/21 20:38:30 by pbonilla         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../includes/ft_printf.h"

char				*fill_s_x(int len, int save, char *s_x, t_param *param)
{
	char			*s;
	int				size;
	int				i;
	int				test;

	test = ft_atoi(s_x);
	if (!(s = malloc(sizeof(char) * (len + 1))))
		return (NULL);
	s[len] = 0;
	ft_printf_memset(s, len, param);
	size = ft_strlen(s_x);
	i = size;
	if (param->minus)
		len = save;
	while (--len >= 0 && --i >= 0)
	{
		if (!(s_x[i] == '0' && !param->prec && !test && s_x[0] == '0'))
			s[len] = s_x[i];
	}
	while (param->prec-- > size)
		s[len--] = '0';
	free(s_x);
	return (s);
}

char				*ft_x_case(t_param *param, unsigned long i)
{
	int				save;
	int				len;
	char			*s_ui;
	char			*s_x;

	s_ui = ft_u_itoa(i);
	if (param->type == 'x')
		s_x = ft_convert_base(s_ui, "0123456789", "0123456789abcdef");
	else
		s_x = ft_convert_base(s_ui, "0123456789", "0123456789ABCDEF");
	free(s_ui);
	len = ft_strlen(s_x);
	if (i == 0 && param->prec == 0)
		len = 0;
	if (param->prec > len)
		len = param->prec;
	save = len;
	if (param->width > len)
		len = param->width;
	return (fill_s_x(len, save, s_x, param));
}