Modularized and cleaned up code