refactor and bugfixes