More cleanup

More refactoring and bug fixes