Fix a bug with the tidying up
Refactor the code a little bit