Refactor and simplify the main function.