Fix issues and refactor