Reorganized and cleaned the code