Major refactor and tidy up of all code