package koopa.trees.antlr;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.antlr.runtime.tree.CommonTree;

public class CommonTreeSerializer {
	public static void serialize(CommonTree tree, File file) throws IOException {
		TokenTypes types = new ANTLRTokenTypesLoader()
				.load("/koopa/grammars/cobol/antlr/Cobol.tokens");

		Writer writer = new BufferedWriter(new FileWriter(file));

		writer.append("<koopa>\n");
		walk(writer, tree, "  ", types);
		writer.append("</koopa>\n");

		writer.flush();
		writer.close();
	}

	private static void walk(Writer writer, CommonTree tree, String dent,
			TokenTypes types) throws IOException {

		final int type = tree.getType();

		if (types.isLiteral(type) || types.isToken(type)) {
			// TODO Should escape stuff where necessary.
			writer.append(dent + "<t><![CDATA[" + tree.getText() + "]]></t>\n");
			return;
		}

		if (tree.getChildCount() == 0) {
			writer.append(dent + "<" + tree.getText() + " />\n");

		} else {
			writer.append(dent + "<" + tree.getText() + ">\n");

			for (Object child : tree.getChildren()) {
				walk(writer, (CommonTree) child, dent + "  ", types);
			}

			writer.append(dent + "</" + tree.getText() + ">\n");
		}
	}
}

@@ -128,16 +128,45 @@
 eption;%0A
+import java.io.StringWriter;%0A
 import j
@@ -339,16 +339,366 @@
 ption %7B%0A
+%09%09Writer writer = new BufferedWriter(new FileWriter(file));%0A%09%09serialize(tree, writer);%0A%09%7D%0A%0A%09public static String serialize(CommonTree tree) throws IOException %7B%0A%09%09StringWriter writer = new StringWriter();%0A%09%09serialize(tree, writer);%0A%09%09return writer.toString();%0A%09%7D%0A%0A%09public static void serialize(CommonTree tree, Writer writer)%0A%09%09%09throws IOException %7B%0A
 %09%09TokenT
@@ -798,69 +798,8 @@
 );%0A%0A
-%09%09Writer writer = new BufferedWriter(new FileWriter(file));%0A%0A
 %09%09wr

Extended the serialisation options a little.