Refactor and bug fixes