Various fixes and minor refactor