Fix possible null reference and EOF