Minor code rearranging and refactoring