Tidy up code so things are happening in the correct place