cleaned up and reordered main loop, added comments