Various bugfixes and refactor.