bug fixes and refactor