cleaning code and fixing memory leaks