Pull this whole block out to a static method and make it recursive (see below).