Refactor main function