Misc bug fix, refactoring