Restructure to improve readability, remove gotos.