code cleanup and more thorough error handling