more error checking. refactored