a little refactoring and improved error handling