package matrix;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FontLoader {
	public static LEDFont s_loadFont(InputStream in) throws IOException {
		BufferedReader r = new BufferedReader(new InputStreamReader(in));
		
		String firstLine = r.readLine();
		String[] firstParts = firstLine.split(",");
		
		int width = Integer.parseInt(firstParts[0]);
		int height = Integer.parseInt(firstParts[1]);
		
		LEDFont font = new LEDFont(width, height);
		
		char character = '\0';
		boolean[][] bitmap = new boolean[height][width];
		int currentRow = 0;
		
		String line = null;
		while((line = r.readLine()) != null) {
			if (line.length() == 0) break;
			String[] parts = line.split(",", -1);
			//If the second cell is empty,
			//we know this is specifying a new character
			if (parts[1].equals("")) {
				//Finish the old char
				if (character != '\0') {
					font.addCharacter(character, bitmap);
				}
				//Start a new one
				if (parts[0].length() > 0) character = parts[0].charAt(0);
				else character = '\0';
				bitmap = new boolean[height][width];
				currentRow = 0;
			} else {
				if (parts.length != width) {
					r.close();
					throw new RuntimeException("Illegal width: " + line);
				}
				if (currentRow >= height) {
					r.close();
					throw new RuntimeException("Too many rows for char: " + character);
				}
				for (int i = 0; i < parts.length; i++) {
					bitmap[currentRow][i] = parts[i].equals("1");
				}
				currentRow++;
			}
		}
		
		if (character != '\0') font.addCharacter(character, bitmap);

		
		r.close();
		
		return font;
	}
}
