move cleanup to the cleanup function, refactor a bit for DRY