I know it probably doesn't affect the success of the script, but you're doing some of the app closing twice after the loop.