Reorganize main function