general bugfixes and code refactor