/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   compute.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: gbaconni <gbaconni@42lausanne.ch>          +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/08/21 18:36:54 by gbaconni          #+#    #+#             */
/*   Updated: 2021/08/22 14:00:53 by gbaconni         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "../ft/ft.h"

// cc -Wall -Wextra -Werror -o a.out -L../ft -lft compute.c && ./a.out && rm a.out

char	*ft_strrev(char *str)
{
	int		size;
	int		i;
	int		j;
	char	c;

	size = ft_strlen(str);
	j = 0;
	i = 0;
	while (i < (size / 2))
	{
		j = size - 1 - i;
		c = str[i];
		str[i] = str[j];
		str[j] = c;
		i++;
	}
	return (str);
}

char	ft_nextchar(char *str)
{
	char	c;

	if (*str != '\0')
		c = *str++;
	else
		c = *str;
	return (c);
}

char	*ft_one_zeros(int n)
{
	char	*str;
	char	*start;

	str = (char *) malloc((n + 2) * sizeof(char));
	start = str;
	*str++ = '1';
	while (n > 0 && n--)
		*str++ = '0';
	*str = '\0';
	str = start;
	return (str);
}

#define DEBUG 1

char	*ft_split3(char *str)
{
	char	*num;
	char	c;
	int		i;
	int		len;

	i = 0;
	len = ft_strlen(str);
	while (*str != '\0' && i < len % 3 && len % 3 != 0 && len > 3)
	{
		len = ft_strlen(str);
		c = ft_nextchar(str);
		ft_putchar(c);
		str++;
		i++;
	}
	if (i != 0)
	{
		ft_putstr("'");

		num = ft_one_zeros(ft_strlen(str) - 1);
#if DEBUG > 0
		printf("\nzeros=%s\n", num);
#endif
		free(num);
	}
	i = 0;
	while (*str != '\0')
	{
		c = ft_nextchar(str);
		ft_putchar(c);
		if (i % 3 == 2 && i < len - 1)
		{
			ft_putstr("'");
			num = ft_one_zeros(ft_strlen(str) - 1);
#if DEBUG > 0
			printf("\nzeros=%s\n", num);
#endif
			free(num);
		}
		str++;
		i++;
	}
	return (str);
}

int	main(int argc, char *argv[])
{
	char	*str;

	if (argc < 2)
		return (1);
	
	str = argv[1];
	ft_putstr(str);
	ft_putstr(" => ");
	(void) ft_split3(str);
	ft_putstr("\n");
	return (0);
}
