Large scale refactor of all the pieces