Improve formatting and misc refactoring