shitloads of refactoring work to get rid of some very ugly code