Refactored main loop and initialization