Code drop: refactoring, bugfixes, and tests