Fixed the order and ensured the app closes correctly in every end case.