debugged and cleaned up