Memory leaks and errors corrected