Reorganized and cleaned up code in preparation for input handling