Refactored goto function (On line 518 in refactored version). Codesmell: long function. Extracted several funtions.