aboutsummaryrefslogtreecommitdiffstats
path: root/src/common/main.c
blob: 5f725891c2cf1da1f891894b7421e8eb2e808e21 (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
#include "aoc.h"
#include "util.h"
#include <err.h>
#include <stdio.h>

struct aoc aoc;

int
main(int argc, const char **argv)
{
	const char *envvar;
	FILE *f;

	if (argc <= 1) {
		fprintf(stderr, "Usage: main PART [ARG]..\n");
		exit(0);
	}

	aoc.part = atoi(argv[1]);
	aoc.argc = argc - 2;
	aoc.argv = &argv[2];

	envvar = getenv("AOC_DEBUG");
	aoc.debug = envvar ? atoi(envvar) : 0;

	/* parse user input */
	aoc.inputfile = getenv("AOC_INPUT");
	if (!aoc.inputfile) aoc.inputfile = "input";
	else aoc_debug("Using input file: '%s'\n", aoc.inputfile);

	/* read input file */
	if (!(f = fopen(aoc.inputfile, "r")))
		err(1, "fopen %s", aoc.inputfile);
	readall(f, (void**) &aoc.input, &aoc.input_size);
	fclose(f);

	/* add null terminator */
	aoc.input = realloc(aoc.input, aoc.input_size + 1);
	if (!aoc.input) err(1, "realloc");
	aoc.input[aoc.input_size] = '\0';

	/* call solution */
	aoc.answer = NULL;
	aoc.solution = NULL;
	if (aoc.part == 1) part1();
	else if (aoc.part == 2) part2();
	else errx(1, "Invalid part number");

	/* check answer if given */
	if (aoc.answer) {
		printf("%s\n", aoc.answer);
		if (!strcmp(aoc.inputfile, "input")) {
			if (aoc.solution && strcmp(aoc.answer, aoc.solution))
				errx(1, "Incorrect solution!");
			else if (!aoc.solution)
				errx(1, "Solution missing!");
		}
	}

	free(aoc.answer);
	free(aoc.input);
}