Refactor some internals