Fixing script exiting and not finishing