Fixed some mistakes and improved error checking.