Reorganized and cleaned up some code