/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: tomoron <marvin@42.fr>                     +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/07/30 12:35:34 by tomoron           #+#    #+#             */
/*   Updated: 2023/07/30 22:40:03 by tomoron          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */
#include "header.h"

char	*ft_parse_nbr(char *nbr)
{
	char	*res;
	int		i;
	int		j;
	int		len;
	int		sign;

	i = 0;
	sign = 1;
	while (nbr[i] == '-' || nbr[i] == '+')
	{
		if (nbr[i] == '-')
			sign *= -1;
		nbr++;
	}
	len = 0;
	while (nbr[i + len] >= '0' && nbr[i + len] <= '9')
		len ++;
	res = malloc((len + 1) * sizeof(char));
	j = 0;
	while (res && nbr[i] >= '0' && nbr[i] <= '9')
		res[j++] = nbr[i++];
	if (res)
		res[j] = 0;
	return (res);
}

void	ft_pre_prep_algo(char *filename, char *nbr)
{
	char	**dict;
	char	*number;

	dict = ft_parse_dict(filename);
	if (!dict)
	{
		ft_putstr("Dict Error\n");
		return ;
	}
	number = ft_parse_nbr(nbr);
	if (number && !ft_number_is_printable(number, dict))
	{
		ft_free_arr_arr(dict);
		if (number)
			free(number);
		return ;
	}
	ft_prep_algo(dict, number);
	ft_free_arr_arr(dict);
	free(number);
}

char	*ft_realloc(char c, char *str)
{
	t_ulli	len;
	t_ulli	i;
	char	*new_str;

	len = ft_strlen(str);
	i = 0;
	new_str = malloc((len + 2) * sizeof(char));
	while (i < len)
	{
		new_str[i] = str[i];
		i++;
	}
	new_str[i] = c;
	new_str[i + 1] = 0;
	free(str);
	return (new_str);
}

void	stdin_mode(char *filename)
{
	char	c;
	char	*str;

	str = malloc(1 * sizeof(char));
	str[0] = 0;
	while (read(0, &c, 1))
	{
		if (c != '\n')
			str = ft_realloc(c, str);
		else
		{
			ft_pre_prep_algo(filename, str);
			free(str);
			str = malloc(1 * sizeof(char));
			str[0] = 0;
		}
	}
}

int	main(int argc, char **argv)
{
	char	*filename;

	filename = "en.dict";
	if (argc <= 1)
		stdin_mode(filename);
	else if (argc == 2)
		ft_pre_prep_algo(filename, argv[1]);
	else if (argc == 3)
		ft_pre_prep_algo(argv[1], argv[2]);
}