bugfixes and minor refactor