Cleanup, minor optiomizations and refactoring