Refactor and bugfixes