-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
75 lines (67 loc) · 2.14 KB
/
main.c
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
#include <ncurses.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include "cpu_chip_8.h"
#define required_input_ext "ch8"
static void print_usage(void) {
fprintf(stderr, "Usage:\t./chip_8 [-p input.ch8] [-d debug_filename]\n");
fprintf(stderr, "\t(.ch8 file extension is required)\n");
}
// http://stackoverflow.com/questions/4849986/how-can-i-check-the-file-extensions-in-c
int ends_with(const char *name, const char *extension, size_t length) {
const char *ldot = strrchr(name, '.');
if (ldot != NULL) {
if (length == 0) {
length = strlen(extension);
}
return strncmp(ldot + 1, extension, length) == 0;
}
return 0;
}
// sudo apt-get install libncurses5-dev
// http://stackoverflow.com/questions/4025891/create-a-function-to-check-for-key-press-in-unix-using-ncurses
// https://viget.com/extend/game-programming-in-c-with-the-ncurses-library
int main(int argc, char **argv) {
char *debug_filename = NULL;
char *input_filename = NULL;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "d:p:")) != -1) {
switch (c) {
case 'd':
debug_filename = optarg;
break;
case 'p':
input_filename = optarg;
break;
case '?':
fprintf(stderr, "Unknown option: %c\n", optopt);
print_usage();
return 1;
default:
print_usage();
return 1;
}
}
if (optind < argc || input_filename == NULL || (ends_with(input_filename, required_input_ext, 0) != 1)) {
print_usage();
return 1;
}
FILE *input_file = fopen(input_filename, "rb");
if (!input_file) {
fprintf(stderr, "Fatal error when opening input file: '%s'\n", argv[1]);
exit(1);
}
FILE *debug_file = NULL;
if (debug_filename) {
debug_file = fopen(debug_filename, "w");
}
chip_8_cpu cpu = initialize_cpu();
initialize_memory(cpu, input_file);
fclose(input_file);
execute_loop(cpu, debug_file);
free_cpu(cpu);
return EXIT_SUCCESS;
}