about summary refs log tree commit diff
path: root/dump.c
blob: 0eefc3c7a98c7460bbf9ea70166f15f60d3e005d (plain) (blame)
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
/* Copyright (C) 2019  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>

#include "cards.h"

int main(int argc, char *argv[]) {
	FILE *file = stdin;
	if (argc > 1) {
		file = fopen(argv[1], "r");
		if (!file) err(EX_NOINPUT, "%s", argv[1]);
	}

	size_t cap = 4096;
	void *ptr = malloc(cap);
	if (!ptr) err(EX_OSERR, "malloc");

	size_t len = 0, read;
	while (0 < (read = fread(&ptr[len], 1, cap - len, file))) {
		len += read;
		if (len < cap) continue;
		cap *= 2;
		ptr = realloc(ptr, cap);
		if (!ptr) err(EX_OSERR, "realloc");
	}
	if (ferror(file)) err(EX_IOERR, "fread");
	fclose(file);

	errno = 0;
	int error = cardsLoad(ptr, len);
	if (error && errno) err(EX_OSERR, "cardsLoad");
	if (error) errx(EX_DATAERR, "cannot load cards");

	for (size_t i = 0; i < CardsLen; ++i) {
		if (!cardsData[i].ptr) continue;

		char name[sizeof("00.bmp")];
		snprintf(name, sizeof(name), "%02zd.bmp", i);

		FILE *file = fopen(name, "w");
		if (!file) err(EX_CANTCREAT, "%s", name);

		fwrite(cardsData[i].ptr, cardsData[i].len, 1, file);
		if (ferror(file)) err(EX_IOERR, "fwrite");

		error = fclose(file);
		if (error) err(EX_IOERR, "fclose");
	}
}