Modularized Functionality

Making this code friendlier to debug.