Reorganized code to prep for CPS conversion