Bug fixes and slight refactor