/*	2010-12-04
 */
package gsigml2hnsu;


import java.io.IOException;
import java.io.BufferedReader;

import sigmlinlib.SiGMLInLib;

import hnscnvt.HNSSign;
import hnsgen.GToHNSSignSiGML.GToHNSException;

import static util.HNSUtils.getStdBufReader;
import static util.HNSUtils.getBufReader;
import static util.HNSUtils.readLines;
import static util.HNSUtils.joinLines;
import static util.HNSUtils.toStdOut;
import static util.HNSUtils.signsFromSiGMLDoc;
import static util.HNSUtils.signDocsFromSigns;
import static util.HNSUtils.hnsuFromHNS8;


/** Main class for the (arbitrary) SiGML to Gestural SiGML Converter. */
public class Main {

/** Converts a the manual parts of a Gestural SiGML document into
 * HNS (Unicode) items, one item per line.
 * The source document is assumed to be UTF-8, and is taken from standard
 * input, unless an argument is provided, defining a file system path for
 * it.
 * Each output item is a single line consisting of the string of
 * HNS (Unicode) characters corresponding to (the manual part of)
 * the original HNS SiGML sign, followed by a tab and the sign's gloss
 * name.
 * The result is provided as UTF-8 on standard output.
 */
	public static void main(String[] args) throws IOException {

		final String PATH =
			args == null || args.length == 0 ? null : args[0];

		BufferedReader grdr =
			PATH == null ? getStdBufReader() : getBufReader(PATH);

		String[] gsigml = readLines(grdr);
		String[] hnsu = gSiGMLToHNS(gsigml);
		toStdOut(hnsu);
	}

	private static String[] gSiGMLToHNS(String[] gsigml) {

		final SiGMLInLib SIL = new SiGMLInLib();

		String[][] gsdocs = signDocsFromSigns(signsFromSiGMLDoc(gsigml));
		final int N = gsdocs.length;

		String[] hnsmans = new String[N];
		String[] glosses = new String[N];

		for (int i=0; i!=N; ++i) {
			String gsdoc = joinLines(gsdocs[i]);
			try {
				HNSSign[] hsigns = SIL.gesturalSiGMLToHNS(gsdoc);
				if (hsigns.length == 0) {
					hnsmans[i] = "";
					glosses[i] = "sign_"+i;
					reportGToHErr(i, "sign is not gestural SiGML");
				}
				else {
					HNSSign hs = hsigns[0]; // should be the only element;
					hnsmans[i] = hs.man();
					glosses[i] = hs.gloss();
				//	System.err.println("sign "+i"  gloss="+glosses[i]);
				}
			}
			catch (GToHNSException gtohx) {
				hnsmans[i] = "";
				glosses[i] = "sign_"+i;
				reportGToHErr(i, gtohx.toString());
				System.err.println();
			}
		}

		String[] hnsu = hnsuFromHNS8(hnsmans);

		String[] hlines = new String[N];
		for (int j=0; j!=N; ++j) {
			hlines[j] = hnsu[j]+"\t"+glosses[j];
		}

		return hlines;
	}

	private static void reportGToHErr(int ix, String msg) {

		System.err.println("gSiGMLToHNS() at item "+ix+": "+msg);
	}
}
