added thread cleanup code