We are repeating this cleanup code in different files. I wonder if we could move it to a common function in utils.misc