-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.c
More file actions
103 lines (94 loc) · 2.57 KB
/
Copy pathinput.c
File metadata and controls
103 lines (94 loc) · 2.57 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* input.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sescolas <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/02 14:03:20 by sescolas #+# #+# */
/* Updated: 2017/02/25 17:05:19 by sescolas ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
static int read_tet(int fd, char **tet)
{
int ret;
if (!(*tet = (char *)malloc(22 * sizeof(char))))
return (0);
ft_bzero(*tet, 22);
ret = read(fd, *tet, 21);
return (ret <= 0 ? 0 : ret);
}
static int valid_marker(char *tet, int pos, int *faces)
{
if (pos % 5 != 0)
if (tet[pos - 1] == PIECE_MARKER)
++(*faces);
if ((pos + 1) % 5 != 0)
if (tet[pos + 1] == PIECE_MARKER)
++(*faces);
if (pos > 4)
if (tet[pos - 5] == PIECE_MARKER)
++(*faces);
if (pos < 15)
if (tet[pos + 5] == PIECE_MARKER)
++(*faces);
return (*faces);
}
static int validate(char *tet, int last_tet)
{
int markers_remaining;
int i;
int faces;
faces = 0;
if ((last_tet && tet[20] != '\0') || (!last_tet && tet[20] != '\n'))
return (0);
tet[20] = '\0';
markers_remaining = 4;
i = -1;
while (tet[++i])
{
if ((i + 1) % 5 == 0 && tet[i] != '\n')
return (0);
else if ((i + 1) % 5 != 0)
{
if (tet[i] != PIECE_MARKER && tet[i] != EMPTY_MARKER)
return (0);
if (tet[i] == PIECE_MARKER && valid_marker(tet, i, &faces))
--markers_remaining;
else if (tet[i] == PIECE_MARKER)
return (0);
}
}
return (i == 20 && !markers_remaining && faces >= 6);
}
static void exit_error(void)
{
write(1, "error\n", 6);
exit(1);
}
void read_file(char *path, t_tet **tets, t_env *env)
{
int fd;
char *tet;
if ((fd = open(path, O_RDONLY)) > 0)
{
while (read_tet(fd, &tet) == 21)
{
if (validate(tet, 0))
append_tet(create_tet(++(env->num_tets), tet), tets);
else
break ;
}
if (validate(tet, 1))
append_tet(create_tet(++(env->num_tets), tet), tets);
else
exit_error();
read_tet(fd, &tet);
close(fd);
if (*tet)
exit_error();
}
else
exit_error();
}