reworked the cleanup to fix race conditions