Improved error handling, removed debug code