summaryrefslogtreecommitdiffstats
path: root/tis100.c
blob: 1a14a648a5a1f5efcf555e6540b3e8834e5c385d (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
68
69
70
71
72
73
74
#include "asm.h"
#include "tpu.h"
#include "util.h"

#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

static struct tis tis;
static FILE *tis_stdin = NULL;
static FILE *tis_stdout = NULL;

int (*cleanup)(void) = NULL;
const char *progname = "tis-as";

int
main(int argc, const char **argv)
{
	bool idle, prev_idle;
	int c;

	if (argc < 2 || argc > 4) {
		fprintf(stderr, "Usage: tis-as FILE [STDIN] [STDOUT]\n");
		exit(1);
	}

	if (argc >= 3) {
		tis_stdin = fopen(argv[2], "r");
		if (!tis_stdin) die("fopen '%s':", argv[2]);
	} else {
		tis_stdin = stdin;
	}
	setvbuf(tis_stdin, NULL, _IONBF, 0);

	if (argc >= 4) {
		tis_stdout = fopen(argv[3], "w+");
		if (!tis_stdout) die("fopen '%s':", argv[3]);
	} else {
		tis_stdout = stdout;
	}
	setvbuf(tis_stdout, NULL, _IONBF, 0);

	tis_init(&tis);

	tis_load(&tis, argv[1]);

	tis.stdin_port.out = -1;
	idle = false;
	while (!idle || !prev_idle || tis.stdin_port.attached
			&& tis.stdin_port.reading && !feof(tis_stdin)) {
		if (tis.stdin_port.attached && tis.stdin_port.out < 0) {
			c = getc(tis_stdin);
			if (c >= 0) tis.stdin_port.out = c;
		}

		if (tis.stdout_port.attached && tis.stdout_port.in >= 0) {
			putc(tis.stdout_port.in, tis_stdout);
			tis.stdout_port.in = -1;
		}

		prev_idle = idle;
		idle = !tis_step(&tis);
	}

	fclose(tis_stdin);
	fclose(tis_stdout);

	tis_deinit(&tis);
}