package com.jameslow;

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

public class SmartBufferedReader extends BufferedReader {
	protected Reader in;
	private String lastlineend = null;
	private static final int LF = 10;
	private static final int CR = 13;
	
	public SmartBufferedReader(Reader in) {
		super(in);
		this.in = in;
	}
	public SmartBufferedReader(Reader in, int sz) {
		super(in,sz);
		this.in = in;
	}
	public String readLine() throws IOException {
		StringBuffer result = new StringBuffer();
		int c;
		boolean eol = false;
		lastlineend = null;
		boolean somethingread = false;
		while (!eol && (c = in.read()) != -1) {
			somethingread = true;
			if (c == LF || c == CR) {
				eol = true;
				if (c == CR) {
					lastlineend = ""+(char)CR;
					this.mark(0);
					c = in.read();
					if (c == LF) {
						lastlineend = lastlineend+(char)LF;
					} else {
						this.reset();
					}
				} else {
					lastlineend = ""+(char)LF;
				}
			} else {
				result.append((char)c);
			}
		}
		if (somethingread) {
			return result.toString();
		} else {
			return null;
		}
	}
	public String getLastLineEnd() {
		return lastlineend;
	}
}

