moved defered teardown function to ensure it gets called