Improved error reporting and cleaned up the code