More error checking, refactoring