Main loop refactoring, small fixes