refactor and bug fixes