Added debug mode and additional error handling