heavy refactoring, documentation and a bit of performance