Refactor and small fixes