Bugfixes and refactoring

Self-explanatory.