some refactoring, improved error checking
more error checking