input FILEIO;

outputtemplate := "%j-%03c.eps";
outputformat := "eps";
%outputtemplate := "%j-%03c.svg";
%outputformat := "svg";

prologues := 3;
w = 0.5 mm;
u = 20.0 w;
pad = 0.05;
%defaultfont := "latt1200";
ahlength := 20 w;
ahangle := 45;

def tr (expr a) =
	((a) scaled u yscaled +1)
enddef;

path hexpath;
hexpath := (1, 0) rotated 30;
for i := 1 upto 5:
	hexpath := hexpath -- (point 0 of hexpath) rotated (60 i);
endfor;
hexpath := hexpath -- cycle;

picture heximage;
heximage = image (
	pickup pencircle scaled 2 w;
	draw tr (hexpath scaled 0.9);
);

def pos (expr i, j, k) = begingroup
	pair p;
	p := (0, 0);
	p := p shifted ((i, 0) rotated 30);
	p := p shifted ((j, 0) rotated 150);
	p := p shifted ((k, 0) rotated 270);
	p
endgroup enddef;

def hex (expr i, j, k) = begingroup
	draw heximage shifted tr (pos (i, j, k));
endgroup enddef;

def board (expr n) = begingroup
	for i := -n upto n:
		for j := -n upto n:
			for k := -n upto n:
				if (i + j + k = 0):
					hex (i, j, k);
					label (decimal (a[i][j])
					    infont defaultfont scaled 4.0,
					    tr (pos (i, j, k)));
				fi;
			endfor;
		endfor;
	endfor;
endgroup enddef;

def process (expr f) = begingroup
	numeric a [] [], b [] [];
	numeric m, n, r, i, j, k;
	path bounds;
	string cmd;

	read_line (f);
	n := get_num - 1;

	for i := -n upto n:
		read_line (f);
		for j := -n upto n:
			for k := -n upto n:
				if (i + j + k = 0):
					a[j][k] := get_num;
				fi;
			endfor;
		endfor;
	endfor;

	read_line (f);
	draw image (board (n));
	for s := 1 upto length buf:
		currentpicture := currentpicture shifted tr ((-3 n, 0));
		cmd := substring (s - 1, s) of buf;
		pickup pencircle scaled 5 w;
		drawarrow (tr ((-1, 0) -- (1, 0)));
		label (cmd infont defaultfont scaled 5.5,
		    tr ((0, 1.5)));
		currentpicture := currentpicture shifted tr ((-3 n, 0));

		for i := -n upto n:
			for j := -n upto n:
				for k := -n upto n:
					if (i + j + k = 0):
						b[j][k] := a[j][k];
					fi;
				endfor;
			endfor;
		endfor;

		for i := -n upto n:
			for j := -n upto n:
				for k := -n upto n:
					if (i + j + k = 0):
						if (cmd = "L"):
							a[j][k] := b[-i][-j];
						elseif (cmd = "R"):
							a[j][k] := b[-k][-i];
						elseif (cmd = "T"):
							a[j][k] := b[k][j];
						fi;
					fi;
				endfor;
			endfor;
		endfor;

		draw image (board (n));
	endfor;

	read_line (f); % EOF

endgroup enddef;

beginfig (1)
	process ("001.input.txt");
	currentpicture := currentpicture shifted -llcorner (currentpicture);
endfig;

end.
