OK, turing.

<- leave blank

Mon Feb 11 14:56:57 EST 2019

#include <u.h>
#include <libc.h>
#include <stdio.h>

char* readnflip(char *in) {
	int c;
	char *buf = calloc(1, sizeof(char));
	char *p, *s;
	char *q;
	Rune r; int l, i, j;
	static char *st;
	int L = 1;

	for (q = in; *q != '\0'; q++) {
		c = *q;
		switch (c) {
		case '(':
			p = readnflip(q + 1);
			q = st;
			l = strlen(p);
			buf = realloc(buf, l + L);
			for (i = 0; i < l; i += j) {
				j = chartorune(&r, &p[i]);
				if (r == Runeerror) {
					buf[L+l-i-2] = p[i];
					continue;
				}
				runetochar(&buf[L+l-i-j-1], &r);
			}
			L += l;
			free(p);
			buf[L-1] = '\0';
			break;
		case ')':
		case '\n':
			st = q;
			return buf;
		default:
			L++;
			buf = realloc(buf, L);
			buf[L-1] = '\0';
			buf[L-2] = c;
			break;
		}
	}
	return buf;
}

void main() {
	char *t;
	char *s = malloc(1024);

	while(fgets(s, 1023, stdin) != nil) {
		t = readnflip(s);
		printf("%s\n", t);
		free(t);
	}

	exits(nil);
}