Refactor and fix bug in dealing with toplevel function definition