@Override
	public void write(NgramLM lm, OutputStream os) throws IOException {

		out = new PrintStream(os);
		sb = new StringBuffer();
		br = System.getProperty("line.separator");
		this.lm = lm;

		// identity variables
		printOne("name", lm.getName(), null);
		printOne("symbol", lm.getSymbol(), null);
		printOne("pattern", (lm.getRegex() == null?null:lm.getRegex().toString()), null);

		// n-gram variables
		int n = lm.getN();
		printOne("n", n+"", null);
		printOne("smoother", (lm.getSmoother()==null?null:lm.getSmoother().getClass().getName()), null);
		printOne("smooth_unigrams", ""+(lm.getSmoother()==null?false:lm.getSmoother().getSmoothUnigrams()), "false");

		// setting variables
		printOne("closed", lm.isClosed()+"", "false");
		printOne("count_terminals", lm.getCountTerminals()+"", "true");
		printOne("max_length", lm.getMaxLength()+"", "0");

		// vocab variables
		printOne("vocab_cutoff", lm.getVocabFrequency()+"", null);
		printOne("vocab_size_limit", lm.getVocabLimit()+"", "0");
		printOne("start_symbol", lm.getStartSymbol()+"", null);
		printOne("terminal_symbol", lm.getTerminalSymbol()+"", null);

		// other language models
		LanguageModel[] ukModels = lm.getUnknownModels();
		if(ukModels == null)
			printOne("unknown_symbol", lm.getUnknownSymbol()+"", null);
		else
			printOne("unknown_model_count", ukModels.length+"", null);

		ClassMap cm = lm.getClassMap();
		if(cm != null) {
			sb.append("[classmap]").append(br);
			out.print(sb.toString());
			sb = new StringBuffer();
			TextStreamClassMapWriter tscmw = new TextStreamClassMapWriter(os, lm.getVocab());
			tscmw.writeClassMap(cm);
		}
		
		// start the data and print the counts
		int[] counts = lm.getNgramCounts();
		sb.append(startOfData).append(br);
		for(int i = 0; i < counts.length; i++) {
			int myCount = counts[i];
			sb.append("ngram ").append(i+1).append("=").append(myCount).append(br);
		}

		//		// add the root node to the stack
		//		LinkedList<KylmPair<String, NgramNode>> list = new LinkedList<KylmPair<String, NgramNode>>();
		//		list.add(new KylmPair<String, NgramNode>(null, lm.getRoot()));

		// print all levels of the nodes
		vocab = lm.getVocab();
		for(int i = 1; i <= n; i++) {
			sb.append("\\").append(i).append("-grams: ").append(br);
			printLevel(lm.getRoot(), null, i, i != n);
			sb.append(br);
		}

		sb.append(endOfData);
		out.println(sb.toString());

		// print the unknown models if they exist
		if(ukModels != null) {
			for(LanguageModel sub : ukModels) {
				out.println();
				write((NgramLM)sub, os);
			}
		}

		out.flush();

	}