Some error checking, refactoring