aboutsummaryrefslogtreecommitdiff
path: root/tsalis/src/tsalis.c
blob: ab24c61b1954c44ee607cdf540dbe7c904420c12 (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
111
112
113
114
115
116
117
118
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <curses.h>
#include <salis.h>
#include "printer.h"
#include "handler.h"
#include "tsalis.h"

#define DEFAULT_ORDER 16

sbool g_exit;
sbool g_running;
sword g_autoSaveInterval;
char  g_simName[NAME_MAX_SIZE + 1] = "def.sim";

static void
onDefault(void)
{
	FILE *testFile = fopen(g_simName, "r");

	if (testFile) {
		fclose(testFile);
		s_load(g_simName);
	} else {
		s_init(DEFAULT_ORDER);
	}
}

static void
onLoad(const char *fileName)
{
	FILE *testFile;

	if (strlen(fileName) > NAME_MAX_SIZE) {
		fputs("ERROR: File name too long", stderr);
		exit(1);
	}

	strncpy(g_simName, fileName, NAME_MAX_SIZE);
	testFile = fopen(g_simName, "r");

	if (testFile) {
		fclose(testFile);
		s_load(g_simName);
	} else {
		fputs("ERROR: File does not exist", stderr);
		exit(1);
	}
}

static void
init(int argc, char **argv)
{
	if (argc == 1) {
		onDefault();
	} else if (argc == 2) {
		char  cmd = argv[1][0];
		char *val = &argv[1][1];

		if (cmd == 'n') {
			s_init(atoi(val));
		} else if (cmd == 'l') {
			onLoad(val);
		} else {
			fputs("ERROR: Incorrect arguments", stderr);
			exit(1);
		}
	} else {
		fputs("ERROR: Incorrect argument count", stderr);
		exit(1);
	}

	tsp_init();
}

static void
exec(void)
{
	while (!g_exit) {
		if (g_running) {
			clock_t beg = clock();
			clock_t end;
			float   delay;

			do {
				s_cycle();

				if (g_autoSaveInterval && !(s_getCycle() % g_autoSaveInterval)) {
					s_save(g_simName);
				}

				end   = clock();
				delay = (float)(end - beg) / CLOCKS_PER_SEC;
			} while (delay < (1.0 / 60.0));
		}

		tsp_printData();
		tsh_handleEvent(getch());
	}
}

static void
quit(void)
{
	tsp_quit();
	s_save(g_simName);
	s_quit();
}

int
main(int argc, char **argv)
{
	init(argc, argv);
	exec();
	quit();
	return 0;
}