Bug fix and minor refactor