Final refactor and tidy up of code