Refactored main loop, commented code