some reordering and refactoring