refactoring, added more error checking