Modularized ugly code into a less-ugly subroutine and fixed top-level return.