#include "fdf.h"

void	z_amplitude(t_fdf*fdf, int i)
{
	if (i > fdf->max_z)
		fdf->max_z = i;
	if (i < fdf->min_z)
		fdf->min_z = i;
}

int	**split_to_map(t_fdf *fdf, char *raw)
{
	int		i;
	int		j;
	int		**map;

	map = ft_calloc(fdf->map_height, sizeof(map));
	if (!map)
		shut_down(fdf);
	i = -1;
	while (++i < fdf->map_height)
	{
		map[i] = ft_calloc(fdf->map_width, sizeof(*map));
		j = -1;
		while (++j < fdf->map_width)
		{
			while (*raw == ' ' || *raw == '!')
				raw++;
			map[i][j] = ft_atoi(raw);
			while (ft_isdigit(*raw) || *raw == '-')
				raw++;
			raw += is_color(raw);
			z_amplitude(fdf, map[i][j]);
		}
	}
	return (map);
}

int	is_color(char *color)
{
	int	i;

	i = 0;
	if (!ft_strncmp(color, ",0x", 3))
		i += 3;
	while (ft_isalnum(color[i]))
		i++;
	return (i);
}

void	size_map(t_fdf *fdf, char *raw, int height)
{
	int	i;
	int	j;

	if (height == 0)
		shut_down(fdf);
	i = 0;
	while (raw[i] && raw[i] != '!')
	{
		while (raw[i] == ' ')
			i++;
		if (raw[i] == '-')
			i++;
		while (ft_isdigit(raw[i]))
			i++;
		i += is_color(raw + i);
		j++;
	}
	fdf->map_width = j;
	fdf->map_height = height;
	fdf->min_z = 0;
	fdf->max_z = 0;
}

int	**parse_map(t_fdf *fdf, int fd)
{
	int		height;
	int		ret;
	char	*line;
	char	*raw;
	int		**map;

	height = 0;
	ret = 1;
	line = NULL;
	raw = ft_strdup("");
	while (ret > 0)
	{
		ret = ft_gnl(fd, &line);
		if (ret > 0)
		{
			height++;
			raw = ft_strjoinfree(raw, line);
			raw = ft_strjoinfree(raw, ft_strdup("!"));
		}
	}
	size_map(fdf, raw, height);
	map = split_to_map(fdf, raw);
	free(line);
	free(raw);
	return (map);
}
