public static String normalizeNewlines(String input) {
		String result = input;
		if (input != null) {
			char[] chars = input.toCharArray();
			final int length = chars.length;

			int startWritePos = 0;

			StringBuffer resultBuffer = null;

			char previousChar = 0;
			for (int index = 0; index < length; index++) {
				char ch = chars[index];
				switch (ch) {
				case '\r':
					if (resultBuffer == null) {
						resultBuffer = new StringBuffer();
					}
					resultBuffer.append(chars, startWritePos, index
							- startWritePos);
					if (previousChar != '\n') {
						resultBuffer.append("\n");
						previousChar = ch;
					} else {
						// reset so only pairs are ignored
						previousChar = 0;
					}
					startWritePos = index + 1;
					break;

				case '\n':
					if (resultBuffer == null) {
						resultBuffer = new StringBuffer();
					}
					resultBuffer.append(chars, startWritePos, index
							- startWritePos);
					if (previousChar != '\r') {
						resultBuffer.append("\n");
						previousChar = ch;
					} else {
						// reset so only pairs are ignored
						previousChar = 0;
					}
					startWritePos = index + 1;

					break;

				default:
					previousChar = 0;
					break;
				}
			}

			// Write any pending data
			if (resultBuffer != null) {
				resultBuffer.append(chars, startWritePos, length
						- startWritePos);
				result = resultBuffer.toString();
			}
		}
		return result;
	}