code cleanup and improved error reporting