Fixed memory leaks

Added comments, fixed memory leaks.