class HTMLUtils {

	private static List<Chunk> sanitize(final String str, final boolean preserveWhiteSpace, final boolean replaceNonBreakableSpaces) {
		StringBuilder builder = new StringBuilder();
        StringBuilder whitespaceBuilder = new StringBuilder();
		char[] chars = str.toCharArray();
        ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
		boolean isWhitespace = chars.length > 0 ? Character.isWhitespace(chars[0]) : true;
		for (char c : chars) {
			if (isWhitespace && !Character.isWhitespace(c)) {
                if (builder.length() == 0) {
                    chunkList.add(Chunk.createWhitespace(whitespaceBuilder.toString(), preserveWhiteSpace));
                } else {
                    builder.append(preserveWhiteSpace ? whitespaceBuilder : " ");
                }
                whitespaceBuilder = new StringBuilder();
            }

            isWhitespace = Character.isWhitespace(c);
            if (isWhitespace) {
                whitespaceBuilder.append(c);
            } else {
                builder.append(c);
            }
		}

        if (builder.length() > 0) {
            chunkList.add(new Chunk(replaceNonBreakableSpaces ? builder.toString().replace(Character.valueOf('\u00a0'), Character.valueOf(' ')) : builder.toString()));
        }

        if (whitespaceBuilder.length() > 0) {
            chunkList.add(Chunk.createWhitespace(whitespaceBuilder.toString(), preserveWhiteSpace));
        }

		return chunkList;
	}

}