Bug fixes and refactor