Re-organized code for more logical flow