Fixed error checking, and the code is cleaner