Added more error detection, fixed a bug.