aboutsummaryrefslogtreecommitdiff
path: root/rf.c
blob: 6067373871fa8fa3d215f22ed70086d6a4a19f9c (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
119
120
#include <ctype.h>
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define DEFMAX 300

struct ref {
	char *a;
	char *y;
	char *t;
	char *q;
	char *d;
	char *c;
	char *p;
	char *w;
};

char format_extra[DEFMAX+1];
char format_full[DEFMAX+1];
char format_list[DEFMAX+1];
int refs_s;
struct ref *refs;

void record(char *dest) {
	char c;
	int i;
	i = 0;
	while (read(STDIN_FILENO, &c, 1) != 0 && isspace(c))
		;
	while (read(STDIN_FILENO, &c, 1) != 0)
		dest[i++] = c;
	dest[i] = '\0';
}

int main() {
	char c, *buf, last[4];
	int i, buf_s, ref_i;

	buf_s = 200;
	buf = malloc((buf_s+1) * sizeof(char));
	if (buf == NULL) err(1, "malloc");

#define reset(n) do { \
	strncpy(last, "    ", 4); \
	i =- n; \
	buf[i] = '\0'; \
} while (0)

	i = 0;
	ref_i = -1;

next:
	while (read(STDIN_FILENO, &c, 1) != 0) {
		if (strncmp(last, "\n.F", 3) != 0)
			goto ref;

		/* record format def */
		switch (last[4]) {
		case 'f':
			record(format_full);
			break;
		case 'x':
			record(format_extra);
			break;
		case 'l':
			record(format_list);
			break;
		default:
			goto add;
		}
		reset(3);
		goto next;

ref:
		if (strncmp(last, "\n.R", 3) != 0)
			goto add;

		/* record reference def */
		switch(last[4]) {
		case 'a':
			reset(3);
			if (ref_i+1 > refs_s) {
				refs_s += 10;
				refs = realloc(refs, refs_s*sizeof(struct ref));
				if (refs == NULL) err(1, "realloc");
			}
			ref_i++;
			refs[ref_i].a = malloc((DEFMAX+1) * sizeof(char));
			if (refs[ref_i].a == NULL) err(1, "malloc");
			record(refs[ref_i].a);
			break;
		case 'y':
			break;
		default:
			goto add;
		}
		reset(3);
		goto next;

add:
		/* add to buffer */
		if (i+1 > buf_s) {
			buf_s += 100;
			buf = realloc(buf, (buf_s+1) * sizeof(char));
			if (buf == NULL) err(1, "realloc");
		}
		buf[i++] = c;

		/* keep track of last 4 characters */
		if (i <= 4) last[i] = c;
		else {
			memmove(last, last+1, 3);
			last[3] = c;
		}
	}
}