some code cleanup and error handling changes