Refactor: order functions and flow