Backported and fixed this code from the augrewrite branch to clean up the function