Refactor and bugfix