/* pf_utils.c */

#include "pf_private_header.h"
#include "libft.h"

/*
** SPECIFIER :
**  receive a word as a string, check if it start by '%', and return the
**  specifier (diuxXspefgn) and the length (h hh l ll)
** -if s is a string, or is a single '%'
**  return NULL (to print is as a string)
** -if s is a double '%%', remove one '%', and
**  return NULL (to print is as a string)
** -then s is a conversion, go to the length and specifier
** -copy them in 'string'
** -and remove them from s
** -return the length and specifier in a string
*/
char *pf_specifier(char *s)
{
    char *string;
    int i;

    if (s[0] != '%' || s[1] == '\0')
        return (NULL);
    if (s[1] == '%')
    {
        s[1] = '\0';
        return (NULL);
    }
    i = 1;
    while (ft_strchr("#0- +'0123456789.*", s[i]) != NULL)
        i++;
    string = ft_strdup(s + i);
    while (s[i] != '\0')
    {
        s[i] = '\0';
        i++;
    }
    return (string);
}

/*
** print the string
** because of lake of space, it also free 'type'
*/
int pf_put_word(int fd, char *s, char *type, int size)
{
    int i;

    i = 0;
    while (i < size)
        write(fd, &(s[i++]), 1);
    free(type);
    free(s);
    return (i);
}

/*
** because of lake of space...
** -1 expand the specifier according to its type and its length
**    and put in a string 'print'
** -2 transform 'print' according to the flags
*/
char *pf_convert_with_flags(char *s, va_list ap, char *type, int *size)
{
    char *print;

    if (!(print = pf_convert(ap, type, &s)))
        return (NULL);
    if (!(print = pf_flag_transform(s, print, type, size)))
        return (NULL);
    free(s);
    return (print);
}