aboutsummaryrefslogtreecommitdiffstats
path: root/src/ft_get_map.c
blob: ff16df1cb379d5ec3cc1963745cb3b542c3a7479 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <libft.h>
#include <cub3d.h>
#include <stddef.h>
#include <stdlib.h>

static int
ft_linecpy(char *line, char *mapl, size_t start)
{
	size_t	i;
	size_t	j;

	i = 0;
	j = start;
	while (i < ft_strlen(line) && line[i])
	{
		mapl[j] = line[i];
		i += 2;
		j++;
	}
	mapl[j] = '\n';
	return (0);
}

static int
ft_check_err(char *line, size_t size)
{
	size_t	i;

	i = 1;
	if (ft_strlen(line) != size || line[0] != '1'
		|| line[ft_strlen(line) - 1] != '1')
		return (-1);
	while (i < ft_strlen(line) && line[i])
	{
		if (line[i] != ' ')
			return (-1);
		i += 2;
	}
	return (0);
}

static char
*ft_get_first_line(char *line, t_cub *clist)
{
	size_t	i;
	char	*mapl;

	i = 0;
	while (i < ft_strlen(line) && line[i])
	{
		if (line[i] != '1' && line[i] != '\0')
			return (NULL);
		i += 2;
	}
	clist->map_w = ft_strlen(line);
	if (clist->map_w <= 2 || ft_check_err(line, clist->map_w) < 0)
		return (NULL);
	if (!(mapl = (char*)malloc(((clist->map_w / 2) + 2) * sizeof(char))))
		return (NULL);
	ft_linecpy(line, mapl, 0);
	ft_memdel(line);
	return (mapl);
}

static char
*ft_get_core_map(char *line, char *mapl, size_t i, t_cub *clist)
{
	if (ft_check_err(line, clist->map_w) < 0)
	{
		ft_memdel(line);
		ft_memdel(mapl);
		return (NULL);
	}
	if (!(mapl = (char*)ft_nrealloc(mapl, (((clist->map_w / 2) + 2) * i)
				* sizeof(char), ((((clist->map_w / 2) + 2) * i) +
				(clist->map_w / 2) + 2) * sizeof(char))))
		return (NULL);
	ft_linecpy(line, mapl, ((clist->map_w / 2) + 2) * i);
	ft_memdel(line);
	return (mapl);
}

int
ft_get_map(int fd, t_cub *clist)
{
	size_t	i;
	int		ret;
	char	*line;
	char	*mapl;

	if ((ret = get_next_line(fd, &line)) <= 0 ||
		!(mapl = ft_get_first_line(line, clist)))
	{
		ft_memdel(line);
		return (-1);
	}
	i = 1;
	while (ret > 0)
	{
		ret = get_next_line(fd, &line);
		if (!(mapl = ft_get_core_map(line, mapl, i, clist)))
			return (-1);
		i++;
	}
	mapl[(i * ((clist->map_w / 2) + 2)) - 1] = '\0';
	ft_free_words(clist->map, NULL);
	clist->map = ft_split(mapl, '\n');
	ft_memdel(mapl);
	return (0);
}