Refactor and fixes