package edu.jhu.thrax.util;

import java.util.Map;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

import edu.jhu.thrax.ThraxConfig;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;

public class FormatUtils {

	private static final String DELIM = String.format(" %s ",
			ThraxConfig.DELIMITER);

	public static boolean isNonterminal(String token) {
		return (token.charAt(0) == '[')
				&& (token.charAt(token.length() - 1) == ']');
	}

	public static String stripNonterminal(String nt) {
		return nt.substring(1, nt.length() - 1);
	}

	public static String stripIndexedNonterminal(String nt) {
		return nt.substring(1, nt.length() - 3);
	}

	public static int getNonterminalIndex(String nt) {
		return Integer.parseInt(nt.substring(nt.length() - 2, nt.length() - 1));
	}

	public static String markup(String nt) {
		return "[" + nt + "]";
	}

	public static String markup(String nt, int index) {
		return "[" + nt + "," + index + "]";
	}

	public static Text ruleToText(RuleWritable r, Map<Text, Writable> fs,
			boolean label, boolean sparse) {
		if (r == null)
			throw new IllegalArgumentException("Cannot convert a null "
					+ "rule to Text.");
		StringBuilder sb = new StringBuilder();
		sb.append(r.lhs);
		sb.append(DELIM);
		sb.append(r.source);
		sb.append(DELIM);
		sb.append(r.target);
		sb.append(DELIM);
		for (Text t : fs.keySet()) {
			double score;
			if (fs.get(t) instanceof DoubleWritable) {
				score = ((DoubleWritable) fs.get(t)).get();
			} else if (fs.get(t) instanceof IntWritable) {
				score = ((IntWritable) fs.get(t)).get();
			} else {
				throw new RuntimeException("Expecting either double or integer " +
						"feature values.");
			}
			if (score == 0.0) {
				if (sparse)
					continue;
				score = 0;
			}
			if (label)
				sb.append(String.format("%s=%s ", t, score));
			else
				sb.append(String.format("%s ", score));
		}
		return new Text(sb.substring(0, sb.length() - 1));
	}
}

@@ -1463,22 +1463,22 @@
 )) %7B%0A%09%09%09
-double
+String
  score;%0A
@@ -1534,16 +1534,38 @@
 %09score =
+ String.format(%22%25.5f%22,
  ((Doubl
@@ -1583,32 +1583,33 @@
 fs.get(t)).get()
+)
 ;%0A%09%09%09%7D else if (
@@ -1655,16 +1655,36 @@
 %09score =
+ String.format(%22%25d%22,
  ((IntWr
@@ -1707,16 +1707,17 @@
 )).get()
+)
 ;%0A%09%09%09%7D e
@@ -1840,15 +1840,47 @@
 core
- == 0.0
+.equals(%220.00000%22) %7C%7C score.equals(%220%22)
 ) %7B%0A
@@ -1922,17 +1922,19 @@
 score = 
-0
+%220%22
 ;%0A%09%09%09%7D%0A%09

truncate feature scores on output