/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_int_case.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pbonilla <eirodeis.lepnj@gmail.com>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/03/03 03:23:01 by pbonilla          #+#    #+#             */
/*   Updated: 2021/03/19 19:12:14 by pbonilla         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

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

char				*fill_s_int(char *s, int len, char *s_i, t_param *param)
{
	int				save;
	int				i;
	int				test;

	test = ft_atoi(s_i);
	save = ft_strlen(s_i) - (s_i[0] == '-');
	i = ft_strlen(s_i);
	while (--len >= 0 && --i >= 0 && s_i[i] != '-')
	{
		s[len] = s_i[i];
		if (test == 0 && param->prec == 0)
			s[len] = ' ';
	}
	while (param->prec-- > save)
		s[len--] = '0';
	if (param->zero && param->prec != -1)
		len = 0;
	if (s_i[0] == '-')
		s[len] = '-';
	free(s_i);
	return (s);
}

char				*ft_int_case(t_param *param, int i)
{
	int				save;
	int				len;
	char			*s_i;
	char			*s;

	if (param->prec > -1 && param->zero)
		param->zero = 0;
	s_i = ft_itoa(i);
	len = ft_strlen(s_i) - (s_i[0] == '-');
	if (i == 0 && param->prec == 0)
		len = 0;
	if (param->prec > len)
		len = param->prec;
	len += (s_i[0] == '-');
	save = len;
	if (param->width > len)
		len = param->width;
	if (!(s = malloc(sizeof(char) * (len + 1))))
		return (NULL);
	s[len] = 0;
	ft_printf_memset(s, len, param);
	if (param->minus)
		len = save;
	s = fill_s_int(s, len, s_i, param);
	return (s);
}