slightly debugged and cleaned