Refactor of main loop and debugging.