Refactor and more fixes