factor out common code to run SAO faster