This fairly complicated function was deeply nested and hard to read... (cherry picked from commit 4a49e560)