Improved script exit fix

Still needs more testing.