Reorganized and cleaned code