Refactored to allow running in debug mode