refactor main function