Modularized and cleaned up some code