Reorder code a bit to avoid duplication