/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/01/20 15:19:31 by cchauvet          #+#    #+#             */
/*   Updated: 2023/01/20 17:22:03 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include "../libftx/libftx.h"
#define ALLLOC_SIZE 2000000

char	*ft_tab_int_to_str(int *tab, size_t len)
{
	char	*str;
	size_t	i;

	str = ft_calloc(len / (sizeof(char) * 8) + 1, sizeof(char));
	i = 0;
	while (i < len)
	{
		str[i / (sizeof(char) * 8)] = str[i / (sizeof(char) * 8)] * 2 + tab[i];
		i++;
	}
	return (str);
}

int	ft_is_finished(int *tab, size_t len)
{
	size_t			i;
	unsigned long	sum;

	if (len >= sizeof(char) * 8 && (len % (sizeof(char) * 8)) == 0)
	{
		sum = 0;
		i = len - sizeof(char) * 8;
		while (i < len)
		{
			sum += tab[i];
			i++;
		}
		return (sum == 0);
	}
	return (0);
}

void	handler(int num)
{
	static int		tab[ALLLOC_SIZE];
	static size_t	len = 0;
	char			*str;

	if (len == 0)
		tab[0] = num;
	else
		tab[len] = num == tab[0];
	len++;
	if (ft_is_finished(tab + 1, len - 1))
	{
		str = ft_tab_int_to_str(tab + 1, len - 1);
		ft_printf("%s", str);
		free(str);
		len = 0;
	}
}

int	main(void)
{
	signal(SIGUSR1, handler);
	signal(SIGUSR2, handler);
	ft_printf("PID: %d\n", getpid());
	while (1)
		;
}
