Added comments and fixed memory leaks